import { createServer } from 'node:net';
import { spawn } from 'node:child_process';
import { readFileSync, readlinkSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { setTimeout as delay } from 'node:timers/promises';
import * as Effect from 'effect/Effect';
import * as Stream from 'effect/Stream';
import { CommandId, ThreadId } from '@t3tools/contracts';
import { makeState, rpcClient, runPromise } from './t3.ts';
import { prepareHome } from './start-app.ts';
const side = process.argv[2];
if (!process.env.PROOF_OUTPUT_ROOT) throw new Error('Set PROOF_OUTPUT_ROOT to your scratch directory');
const root = `${process.env.PROOF_OUTPUT_ROOT}/${side}-${Date.now()}`;
mkdirSync(root, {recursive:true});
const home = `${root}/home`, pidFile = `${root}/settle-shell.pid`;
const lines: {time:number,text:string}[] = [];
const began=Date.now();
function log(text:string){lines.push({time:(Date.now()-began)/1000,text}); console.log(text); writeFileSync(`${root}/transcript.json`,JSON.stringify(lines,null,2));}
await runPromise(prepareHome(home));
const probe=createServer(); await new Promise(resolve=>probe.listen(0,'127.0.0.1',resolve)); const port=probe.address().port; await new Promise(resolve=>probe.close(resolve));
const server = spawn(process.execPath,['apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',String(port),'--base-dir',home,'--dev-url','http://127.0.0.1:5733'],{cwd:process.cwd(),env:{...process.env,T3CODE_DEV_SEED:'0',T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:'0',T3CODE_ENVIRONMENT_LABEL:'Settle proof',SHELL:'/bin/bash',PROMPT_COMMAND:'sleep 2'},stdio:['ignore','pipe','pipe']});
let serverLog=''; server.stdout.on('data',x=>serverLog+=x);server.stderr.on('data',x=>serverLog+=x);
try {
  for(let i=0;i<1200 && !existsSync(`${home}/userdata/server-runtime.json`);i++) {if(server.exitCode!==null)throw new Error(serverLog); await delay(100);}
  const {origin}=JSON.parse(readFileSync(`${home}/userdata/server-runtime.json`,'utf8'));
  log(`Linux | real T3 server | ${side} commit ${process.env.PROOF_SHA}`);
  log('Server environment: SHELL=/bin/bash; PROMPT_COMMAND="sleep 2"');
  const state=makeState(home);
  await runPromise(Effect.gen(function*(){const client=yield* rpcClient(home,origin);yield* client['server.updateSettings']({patch:{defaultProjectScripts:[{id:'settle-proof',name:'Record settle shell',command:`echo $$ > ${pidFile}`,icon:'play',runOnWorktreeCreate:false,runOnSettle:true}]}});}).pipe(Effect.scoped));
  const project=await state.state.project('settle-demo');
  log('Created synthetic Git project; configured settle action: echo $$ > <pid-file>');
  const started=await runPromise(state.cli(['thread','start',project,'Say hello','--title','Settle terminal proof','--worktree','main','--provider','devReplay','--model','multi-turn','--wait','--json']));
  const {threadId}=JSON.parse(started.stdout);
  log('Started new worktree thread with Replay (dev); its turn finished.');
  const projection=await runPromise(Effect.gen(function*(){const client=yield* rpcClient(home,origin);return yield* client['orchestration.getThreadProjection']({threadId:ThreadId.make(threadId)});}).pipe(Effect.scoped));
  const worktree=projection.thread.worktreePath;
  await runPromise(Effect.gen(function*(){const client=yield* rpcClient(home,origin);yield* client['orchestration.dispatchCommand']({type:'thread.settle',commandId:CommandId.make(crypto.randomUUID()),threadId:ThreadId.make(threadId)});}).pipe(Effect.scoped));
  log('Dispatched Settle thread through the real app RPC.');
  for(let i=0;i<600 && !existsSync(pidFile);i++)await delay(100);
  const pid=Number(readFileSync(pidFile,'utf8').trim());
  log(`Settle action wrote shell PID ${pid}. Beginning 15-second observation.`);
  function inspect(){try {const cmd=readFileSync(`/proc/${pid}/comm`,'utf8').trim();const stat=readFileSync(`/proc/${pid}/stat`,'utf8');return {alive:!stat.split(') ')[1].startsWith('Z'),command:cmd,cwdMatchesWorktree:readlinkSync(`/proc/${pid}/cwd`)===worktree};}catch{return {alive:false,command:null};}}
  let observation;
  for(let second=1;second<=15;second++){await delay(1000);observation=inspect();log(`+${String(second).padStart(2,'0')}s: shell ${observation.alive?'ALIVE ('+observation.command+')':'EXITED'}`);}
  const metadata=await runPromise(Effect.gen(function*(){const client=yield* rpcClient(home,origin);return yield* Stream.runHead(client['subscribeTerminalMetadata']({}));}).pipe(Effect.scoped));
  const terminals=metadata.value?.terminals?.filter(t=>t.threadId===threadId) ?? [];
  log(`Terminal metadata after 15s: ${terminals.length ? terminals.map(t=>t.status).join(', ') : 'no terminal remains'}`);
  if(observation.alive)log(`Shell current directory still equals thread worktree: ${observation.cwdMatchesWorktree}`);
  log(`RESULT: ${observation.alive?'shell remains alive after successful settle':'shell closed after successful settle'}`);
  writeFileSync(`${root}/result.json`,JSON.stringify({side,sha:process.env.PROOF_SHA,alive:observation.alive,pid,root,threadId},null,2));
  writeFileSync(`${root}/transcript.txt`,lines.map(l=>`[${l.time.toFixed(1)}s] ${l.text}`).join('\n')+'\n');
  console.log(`ARTIFACT_DIRECTORY=${root}`);
} finally { if(server.exitCode===null){server.kill('SIGTERM'); await new Promise(resolve=>server.once('exit',resolve));} writeFileSync(`${root}/server-private.log`,serverLog); }
