import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { expect } from 'e2e';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { makeState, runPromise, test, WEB } from './t3.ts';

// Only the replay model is instrumented: all delegation, questions and renames use real MCP.
async function mcp(server: any, name: string, args: any) {
  const headers = Object.fromEntries((server.headers ?? []).map((h: any) => [h.name, h.value]));
  const post = async (method: string, params: any) => {
    const response = await fetch(server.url, { method: 'POST', headers: { ...headers, ...(server.sessionId ? { 'Mcp-Session-Id': server.sessionId } : {}), 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: crypto.randomUUID(), method, params }) });
    server.sessionId ??= response.headers.get('mcp-session-id');
    const text = await response.text();
    const data = text.split('\n').find((l) => l.startsWith('data:'));
    const body = JSON.parse(data ? data.slice(5) : text);
    if (body.error || body.result?.isError) throw new Error(JSON.stringify(body));
    return body.result;
  };
  if (!server.sessionId) await post('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'question-proof', version: '1' } });
  const result = await post('tools/call', { name, arguments: args });
  return result?.structuredContent;
}

const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));

test('An idle coordinator receives its child question while another coordinator remains busy', WEB, async ({ t3, app, screen }) => {
  const gate = path.join(T3_HOME, 'question-proof');
  await fs.mkdir(gate, { recursive: true });
  const agentPath = path.join(APP_DIR, 'apps/server/scripts/dev-replay-agent.ts');
  const original = await fs.readFile(agentPath, 'utf8');
  let source = original.replace('loadSession: true,', 'loadSession: true, mcpCapabilities: { http: true, sse: true },');
  source = source.replace('sessions.set(sessionId, { cwd, model:', 'sessions.set(sessionId, { mcpServers: params.mcpServers, cwd, model:');
  source = source.replace('code: error.code ?? -32603', 'code: -32603');
  source = source.replace('const turns = loadTurns(session.model);', `
        const proofDir = ${JSON.stringify(gate)};
        const text = JSON.stringify(params.prompt);
        const servers = (session as any).mcpServers;
        const stdio = servers.find((s: any) => s.name === 't3-code');
        const env = Object.fromEntries((stdio?.env ?? []).map((e: any) => [e.name, e.value]));
        const server = servers.find((s: any) => s.type === 'http') ?? { url: env.T3_ACP_MCP_ENDPOINT, headers: [{name: 'Authorization', value: env.T3_ACP_MCP_AUTHORIZATION}] };
        NodeFS.writeFileSync(proofDir + '/debug.json', JSON.stringify({servers, server}));
        if (text.includes('PROOF_COORDINATOR_') && session.promptCount === 0) {
          const label = text.includes('PROOF_COORDINATOR_A') ? 'A' : 'B';
          NodeFS.writeFileSync(proofDir + '/' + label + '-mcp.json', JSON.stringify(server));
          ${mcp.toString()}
          await mcp(server, 'orchestrator_capabilities', {});
          const child = await mcp(server, 'delegate_task', { task: 'PROOF_CHILD_' + label, title: 'Child ' + label, mode: 'async', target: { providerInstanceId: 'devReplay', model: 'question' } });
          NodeFS.writeFileSync(proofDir + '/' + label + '-child.json', JSON.stringify(child));
          send({ method: 'session/update', params: { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Coordinator ' + label + ' is idle; child is preparing its question.' } } } });
          session.promptCount++;
          return { stopReason: 'end_turn' };
        }
        if (text.includes('PROOF_CHILD_') && session.promptCount === 0) {
          const label = text.includes('PROOF_CHILD_A') ? 'A' : 'B';
          NodeFS.writeFileSync(proofDir + '/' + label + '-ready', 'ready');
          while (!NodeFS.existsSync(proofDir + '/' + label + '-ask')) await new Promise(r => setTimeout(r, 50));
        }
        if (session.promptCount > 0 && text.includes('has a question') || session.promptCount > 0 && text.includes('blocked on a question')) {
          send({ method: 'session/update', params: { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'CHILD QUESTION RECEIVED while coordinator A is busy.' } } } });
          return { stopReason: 'end_turn' };
        }
        const turns = loadTurns(session.model);`);
  await fs.writeFile(agentPath, source);
  try {
    const project = await t3.project('Question delivery');
    const { cli } = makeState(T3_HOME);
    const launch = async (label: string) => JSON.parse((await runPromise(cli(['thread', 'start', project, 'PROOF_COORDINATOR_' + label, '--title', 'Coordinator ' + label, '--provider', 'devReplay', '--model', 'multi-turn', '--json']))).stdout);
    const a = await launch('A');
    const b = await launch('B');
    for (const label of ['A','B']) {
      for (let i = 0; i < 600; i++) { if (await fs.stat(path.join(gate, label + '-ready')).catch(() => false)) break; await pause(100); }
      await fs.stat(path.join(gate, label + '-ready'));
    }
    await t3.open(b);
    const serverA = JSON.parse(await fs.readFile(path.join(gate, 'A-mcp.json'), 'utf8'));
    const serverB = JSON.parse(await fs.readFile(path.join(gate, 'B-mcp.json'), 'utf8'));
    let finished = 0;
    const renames = Array.from({ length: 5000 }, (_, i) => mcp(serverA, 't3_thread_update', { action: 'rename', title: 'Busy coordinator A ' + String(i).padStart(4,'0'), clientRequestId: 'busy-' + i }).then(() => { finished++; }));
    await pause(1000);
    await fs.writeFile(path.join(gate, 'A-ask'), 'ask');
    await pause(2000);
    await fs.writeFile(path.join(gate, 'B-ask'), 'ask');
    await pause(3000);
    const controlStart = Date.now();
    await mcp(serverB, 't3_thread_update', { action: 'rename', title: 'Coordinator B — idle, awaiting child question' });
    console.log('B control rename ms', Date.now() - controlStart, 'A renames completed', finished);
    await app.screenshot('idle-coordinator-question');
    try {
      await expect(screen.getByText('CHILD QUESTION RECEIVED while coordinator A is busy.')).toBeVisible({ timeout: 12000 });
      if (finished === 5000) throw new Error('Scenario control: A queue drained before B received its question');
      await app.screenshot('question-arrived-during-busy-queue');
    } finally {
      await Promise.allSettled(renames);
    }
  } finally { await fs.writeFile(agentPath, original); }
});
