import { spawn } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, utimesSync } from 'node:fs';
import { setTimeout as delay } from 'node:timers/promises';
import { CommandId, ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { makeState, rpcClient, runPromise, test, WEB } from './t3.ts';

const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
async function until(check: () => boolean, timeout = 30000) {
  const end = Date.now() + timeout;
  while (!check()) { if (Date.now() > end) throw new Error('Milestone not reached'); await delay(100); }
}
test('A settle action waiting at restart tears down its worktree resource', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('restart-demo', {
    'settle.cjs': `const fs = require('node:fs');
fs.appendFileSync('resource.log', 'settle start\\n');
setTimeout(() => { try { process.kill(Number(fs.readFileSync('.resource.pid','utf8'))); } catch {} fs.writeFileSync('.settle-ran','done'); fs.appendFileSync('resource.log','resource stopped\\n'); },45000);`,
    'inspect.cjs': `const fs = require('node:fs');
console.log('SETTLE QUEUE RESTART — THREAD B');
console.log('Environment: web / Replay (dev) / fresh synthetic data');
console.log('A started first; B queued; server restarted before B started.');
let live = false; try { process.kill(Number(fs.readFileSync('.resource.pid','utf8')),0); live=true; } catch {}
console.log('Resource process: ' + (live ? 'RUNNING' : 'STOPPED'));
console.log('Settle action completed: ' + fs.existsSync('.settle-ran'));
console.log('Settle action log:');
console.log(fs.existsSync('resource.log') ? fs.readFileSync('resource.log','utf8') : '(no log — action never started)');`,
  });
  // Seed through the standard helper before opening; the worktree turns below use the same Replay agent.
  await t3.thread({project, title:'Restart reproduction', messages:['Start']});
  const withClient = (use: (client: Effect.Success<ReturnType<typeof rpcClient>>) => any) => runPromise(rpcClient(T3_HOME, app.baseUrl ?? '').pipe(Effect.flatMap(use), Effect.scoped));
  await withClient(client => client['server.updateSettings']({patch:{defaultProjectScripts:[
    {id:'settle-resource',name:'Stop resource on settle',command:'node settle.cjs',icon:'play',runOnWorktreeCreate:false,runOnSettle:true,async:false},
    {id:'inspect-resource',name:'Inspect resource',command:'clear; node inspect.cjs; sleep 20',icon:'play',runOnWorktreeCreate:false,async:false},
  ]}}));
  const {cli} = makeState(T3_HOME);
  const threads: {threadId:string; path:string}[] = [];
  const resources: ReturnType<typeof spawn>[] = [];
  try {
    for (const name of ['demo-A','demo-B']) {
      const result = await runPromise(cli(['thread','start',project,'Start','--title',name,'--worktree','main','--branch',name,'--provider','devReplay','--model','multi-turn','--wait','--json']));
      const {threadId} = JSON.parse(result.stdout);
      const projection = await withClient(client => client['orchestration.getThreadProjection']({threadId:ThreadId.make(threadId)}));
      const path = projection.thread.worktreePath;
      if (!path) throw new Error('Missing worktree');
      const resource = spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{cwd:path,stdio:'ignore'});
      resources.push(resource);
      writeFileSync(`${path}/.resource.pid`,String(resource.pid));
      threads.push({threadId,path});
    }
    const settle = (threadId:string) => withClient(client => client['orchestration.dispatchCommand']({type:'thread.settle',threadId:ThreadId.make(threadId),commandId:CommandId.make(crypto.randomUUID())}));
    await t3.open(threads[1]!);
    await settle(threads[0]!.threadId);
    await until(()=>existsSync(`${threads[0]!.path}/resource.log`));
    await settle(threads[1]!.threadId);
    await delay(1500);
    if (existsSync(`${threads[1]!.path}/resource.log`) || !resources.every(r=>alive(r.pid!))) throw new Error('B was not queued behind A');
    const runtime = `${T3_HOME}/userdata/server-runtime.json`;
    const before = JSON.parse(readFileSync(runtime,'utf8')).startedAt;
    // The dev launcher owns and stops its captured child when a source timestamp changes.
    const source = `${APP_DIR}/apps/server/src/bin.ts`;
        utimesSync(source,new Date(),new Date());
    await until(()=> {try {return JSON.parse(readFileSync(runtime,'utf8')).startedAt !== before;} catch {return false;}},60000);
    // Past both 45-second commands and the one-minute sweep, matching the reported observation.
    await delay(155000);
    await t3.open(threads[1]!);
    await screen.getByRole('button','Script actions',{exact:true}).tap();
    await screen.getByRole('menuitem',/^Inspect resource/).first().tap();
    await browser.keyboard.press('Escape');
    await screen.getByRole('textbox').first().hover();
    await delay(2500);
    await app.screenshot('queued-settle-after-server-restart');
    expect({completed:existsSync(`${threads[1]!.path}/.settle-ran`), resourceAlive:alive(resources[1]!.pid!)}).toEqual({completed:true,resourceAlive:false});
  } finally {
    for (const resource of resources) if (resource.pid && alive(resource.pid)) resource.kill('SIGTERM');
  }
});
