/**
 * END-TO-END integration test with REAL Claude Code process.
 * This will capture the actual crash-marking behavior with debug logs.
 */

import { describe, it, expect } from 'vitest';
import { execSync } from 'node:child_process';
import { writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import { tmpdir } from 'node:os';

describe('Real E2E Crash Investigation', () => {
  it('should spawn a real agent and capture debug logs', async () => {
    if (!process.env.REAL_CLAUDE_TESTS) {
      console.log('Skipping - REAL_CLAUDE_TESTS not set');
      return;
    }

    console.log('🚀 Starting REAL end-to-end test...');

    // Create test workspace
    const testWorkspace = join(tmpdir(), `e2e-test-${randomBytes(4).toString('hex')}`);
    await mkdir(testWorkspace, { recursive: true });
    await mkdir(join(testWorkspace, '.cw/input'), { recursive: true });

    // Create minimal input that will ask questions
    await writeFile(join(testWorkspace, '.cw/input/manifest.json'), JSON.stringify({
      files: ['initiative.md']
    }));

    await writeFile(join(testWorkspace, '.cw/input/initiative.md'), `---
id: test-e2e
name: E2E Test Initiative
status: active
---`);

    console.log('📁 Created test workspace:', testWorkspace);

    // Change to the workdir where server is running to spawn agent
    const originalCwd = process.cwd();
    process.chdir('/Users/lukasmay/development/projects/codewalk-district/workdir');

    console.log('🎯 Spawning real Claude agent...');
    console.log('📍 Working directory:', process.cwd());

    const agentName = `e2e-test-${randomBytes(4).toString('hex')}`;
    let spawnResult: any;

    try {
      // Spawn agent with shorter timeout for testing - use first available initiative
      const result = execSync(`cw agent spawn --name ${agentName} --initiative 2-x-DkbSjiiRzlSAsD4ib "Please analyze the current admin UI setup and identify what needs to be replaced with shadcn + tailwind"`, {
        encoding: 'utf-8',
        timeout: 30000 // 30 seconds max for testing
      });

      console.log('📄 CLI Output:', result);
      spawnResult = { success: true, output: result };

    } catch (error: any) {
      spawnResult = {
        success: false,
        exitCode: error.status,
        stdout: error.stdout,
        stderr: error.stderr
      };

      console.log('⚠️ CLI execution result:', spawnResult);

      // Timeout is expected for agents that take time to complete
      if (error.status === 124 || error.message?.includes('timeout')) {
        console.log('⏰ Got timeout (expected) - agent was running');
      }
    }

    // Wait a moment for completion detection to run
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Now check the database for what happened
    console.log('📊 Checking agent status in database...');

    const dbPath = '.cw/cw.db'; // From workdir

    try {
      const agentData = execSync(
        `sqlite3 "${dbPath}" "SELECT json_object('id', id, 'name', name, 'status', status, 'exit_code', exit_code, 'worktree_id', worktree_id) FROM agents WHERE name = '${agentName}' ORDER BY created_at DESC LIMIT 1;"`,
        { encoding: 'utf-8' }
      ).trim();

      if (agentData) {
        const agent = JSON.parse(agentData);
        console.log('🔍 Agent found:', agent);

        // Check for output files in agent workdir
        const agentWorkdir = `agent-workdirs/${agentName}`;
        const outputDir = join(agentWorkdir, '.cw/output');

        console.log('📂 Checking output dir:', outputDir);

        try {
          const { existsSync } = await import('node:fs');
          const hasSignal = existsSync(join(outputDir, 'signal.json'));
          console.log('📄 Has signal.json:', hasSignal);

          if (hasSignal) {
            const { readFile } = await import('node:fs/promises');
            const signalContent = await readFile(join(outputDir, 'signal.json'), 'utf-8');
            const signal = JSON.parse(signalContent);
            console.log('📋 Signal status:', signal.status);

            if (agent.status === 'crashed' && ['questions', 'done', 'error'].includes(signal.status)) {
              console.log('🚨 BUG REPRODUCED: Agent crashed despite valid completion!');
              console.log('🔍 This indicates our completion detection race condition bug is still active');
            } else if (agent.status === 'waiting_for_input' && signal.status === 'questions') {
              console.log('✅ CORRECT: Agent properly detected completion and set waiting_for_input');
            }
          }
        } catch (err) {
          console.log('❌ Could not check output files:', err);
        }
      } else {
        console.log('❌ No agent found in database');
      }

    } catch (err) {
      console.log('❌ Database query failed:', err);
    } finally {
      // Restore original working directory
      process.chdir(originalCwd);
    }

    // The test passes regardless - this is for investigation
    expect(true).toBe(true);

  }, 180000); // 3 minutes timeout
});