/// <reference lib="dom" />
import { spawn } from 'node:child_process';
import { createServer } from 'node:net';
import { once } from 'node:events';
import { writeFile } from 'node:fs/promises';
import { CommandId, DEFAULT_TERMINAL_ID, ProviderInstanceId, ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import * as Stream from 'effect/Stream';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { prepareHome } from './start-app.ts';
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from './t3.ts';

const home = `${T3_HOME}-question-source`;
const repository = { '.git/config': '[remote "origin"]\nurl = https://example.com/demo/repo.git\n' };

test('An old question answer is refused after moving the thread', WEB, async ({t3, app, browser, screen}) => {
  const workspace = await t3.project('Question demo', repository);
  await runPromise(prepareHome(home));
  const portServer = createServer();
  portServer.listen(0, '127.0.0.1');
  await once(portServer, 'listening');
  const port = (portServer.address() as {port:number}).port;
  await new Promise<void>(resolve => portServer.close(() => resolve()));
  const host = `http://127.0.0.1:${port}`;
  let child: ReturnType<typeof spawn>;
  const start = async () => {
    child = spawn(process.execPath, ['apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',String(port),'--base-dir',home,'--dev-url',app.baseUrl!], {
      cwd: APP_DIR, env: { PATH: process.env.PATH, HOME: process.env.HOME, T3CODE_DEV_SEED:'0', T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:'0', T3CODE_ENVIRONMENT_LABEL:'Source', T3CODE_ENVIRONMENT_MACHINE_KIND:'laptop' }, stdio:['ignore','pipe','pipe']
    });
    await new Promise<void>((resolve,reject) => {
      let output='';
      child.stdout!.on('data',chunk=> { output+=String(chunk); if (/Token:\s*\S+/.test(output)) resolve(); });
      child.stderr!.on('data',chunk=> process.stderr.write(chunk));
      child.once('exit',code=>reject(Error(`Source exited ${code}`)));
    });
  };
  const stop = async () => { const exited=once(child,'exit'); child.kill('SIGTERM'); await exited; };
  const source = makeState(home);
  const projection = (threadId:string) => runPromise(Effect.gen(function*(){
    const client=yield* rpcClient(home,host);
    const item=yield* client['orchestration.subscribeThread']({threadId:ThreadId.make(threadId)}).pipe(Stream.runHead);
    if(item._tag!=='Some'||item.value.kind!=='snapshot') throw Error('Missing thread');
    return item.value.projection;
  }).pipe(Effect.scoped));
  await start();
  try {
    await runPromise(source.cli(['project','add',workspace,'--title','Question demo']));
    await runPromise(Effect.gen(function*(){
      const primary=yield* rpcClient(T3_HOME,app.baseUrl!);
      const remote=yield* rpcClient(home,host);
      for(const client of [primary,remote]) yield* client['server.updateSettings']({patch:{linkedEnvironmentsEnabled:true}});
      for(const [from,otherHome,url] of [[primary,home,host],[remote,T3_HOME,app.baseUrl!]] as const) {
        const pairing=yield* makeState(otherHome).cli(['auth','pairing','create','--json']);
        yield* from['peerLinks.link']({url,pairingCode:JSON.parse(pairing.stdout).credential,access:'full-access'});
      }
    }).pipe(Effect.scoped));
    const thread=await runPromise(Effect.gen(function*(){
      const client=yield* rpcClient(home,host);
      const shell=yield* client['orchestration.subscribeShell']({}).pipe(Stream.runHead);
      if(shell._tag!=='Some'||shell.value.kind!=='snapshot') throw Error('Missing projects');
      const project=shell.value.snapshot.projects.find(p=>p.workspaceRoot===workspace)!;
      const launched=yield* client['orchestration.launchThread']({commandId:CommandId.make(crypto.randomUUID()),projectId:project.id,title:'Question before move',modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'question'},runtimeMode:'full-access',interactionMode:'default',workspaceStrategy:{type:'root'},initialMessage:{text:'Ask a question',attachments:[]}});
      yield* client['orchestration.subscribeThread']({threadId:launched.threadId}).pipe(Stream.filter(item=>item.kind==='snapshot' ? item.projection.runtimeRequests.some(r=>r.status==='pending') : item.kind==='event'&&JSON.stringify(item.event).includes('runtime-request.updated')),Stream.take(1),Stream.runDrain,Effect.timeout('60 seconds'));
      return {threadId:launched.threadId};
    }).pipe(Effect.scoped));
    await stop();
    await start();
    const initial=await projection(thread.threadId);
    if(!initial.runtimeRequests.some(r=>r.status==='pending'&&r.responseCapability.type==='message')) throw Error('Restart did not leave a message-capable question');
    await browser.addInitScript(() => {
      const requested=Promise.withResolvers<void>();
      const replied=Promise.withResolvers<unknown>();
      let forward=()=>{};
      const send=WebSocket.prototype.send;
      WebSocket.prototype.send=function(data) {
        if(typeof data!=='string'||!data.includes('"runtime-request.respond"')) return send.call(this,data);
        const request=JSON.parse(data);
        this.addEventListener('message',event=> {
          for(const frame of [JSON.parse(String(event.data))].flat()) if(frame._tag==='Exit'&&String(frame.requestId)===String(request.id)) replied.resolve(frame.exit);
        });
        forward=()=>send.call(this,data);
        requested.resolve();
      };
      (window as any).answerGate={requested:requested.promise,release:()=>{forward(); return replied.promise;}};
    });
    const via=await runPromise(environmentId(app.baseUrl!));
    const target=await runPromise(environmentId(host));
    await t3.open(`/linked/${via}/${target}/${thread.threadId}`);
    await screen.getByRole('button','Connect to interact').tap();
    await screen.getByRole('button', /Strict schemas/).tap();
    await browser.evaluate(()=> (window as any).answerGate.requested.then(()=>null));
    await app.screenshot('question-answer-awaiting-delivery');
    await screen.getByRole('button','Thread actions for Question before move').tap();
    await screen.getByRole('menuitem','Continue on another machine…').tap();
    await screen.getByRole('button',/^Move to /).tap();
    await expect.poll(async()=> (await projection(thread.threadId)).thread.handoff?.state).toBe('departed');
    const answerExit=await browser.evaluate(()=> (window as any).answerGate.release());
    const final=await projection(thread.threadId);
    console.log('QUESTION_MOVE_RESULT',JSON.stringify({answerExit,handoff:final.thread.handoff,runs:final.runs.map(r=>({ordinal:r.ordinal,status:r.status})),requests:final.runtimeRequests.map(r=>({id:r.id,status:r.status,responseCapability:r.responseCapability}))}));
    const original=final.runtimeRequests.find(r=>r.id===initial.runtimeRequests.find(r=>r.status==='pending')!.id);
    const refusal=(answerExit as any).cause?.find((item:any)=>item.error)?.error.message;
    const report=[
      'SOURCE SERVER — ANSWER AFTER THREAD MOVE',
      '',
      `Handoff: ${final.thread.handoff?.state} → ${final.thread.handoff?.label}`,
      `Answer RPC: ${(answerExit as any)._tag}`,
      ...(refusal ? [`Refusal: ${refusal}`] : ['Answer accepted on the source machine.']),
      `Original question: ${original?.status}`,
      `Source runs: ${final.runs.length} (before answer: ${initial.runs.length})`,
      ...final.runs.map(r=>`  Run ${r.ordinal}: ${r.status}`),
      '',
      'Read from the real source server immediately after the answer.',
    ].join('\n');
    const destinationWorkspace=await runPromise(Effect.gen(function*(){
      const client=yield* rpcClient(T3_HOME,app.baseUrl!);
      const item=yield* client['orchestration.subscribeThread']({threadId:ThreadId.make((final.thread.handoff as any).threadId)}).pipe(Stream.runHead);
      if(item._tag!=='Some'||item.value.kind!=='snapshot') throw Error('Missing moved thread');
      return item.value.projection.thread.worktreePath ?? workspace;
    }).pipe(Effect.scoped));
    await writeFile(`${destinationWorkspace}/move-result.txt`,report+'\n');
    await runPromise(Effect.gen(function*(){
      const client=yield* rpcClient(T3_HOME,app.baseUrl!);
      const threadId=ThreadId.make((final.thread.handoff as any).threadId);
      const terminalId=DEFAULT_TERMINAL_ID;
      yield* client['terminal.open']({threadId,terminalId,cwd:destinationWorkspace,cols:120,rows:16});
      yield* client['terminal.write']({threadId,terminalId,data:"printf '\\033[2J\\033[H'; cat move-result.txt; read\n"});
      yield* client['terminal.observe']({threadId,terminalId}).pipe(Stream.map(frame=>JSON.stringify(frame)),Stream.scan(()=>'',(all,part)=>all+part),Stream.filter(all=>all.includes('Read from the real source server immediately after the answer.')),Stream.take(1),Stream.runDrain,Effect.timeout('15 seconds'));
    }).pipe(Effect.scoped));
    await screen.getByRole('button','Toggle terminal drawer').tap();
    await screen.getByRole('textbox','Terminal input').waitFor();
    await browser.evaluate(()=>new Promise(resolve=>setTimeout(resolve,1000)));
    await app.screenshot('answer-after-thread-move');
    expect({exit:(answerExit as any)._tag,pending:final.runtimeRequests.find(r=>r.id===initial.runtimeRequests.find(r=>r.status==='pending')!.id)?.status,runs:final.runs.length}).toEqual({exit:'Failure',pending:'pending',runs:initial.runs.length});
  } finally { await stop(); }
});
