import { expect } from "e2e";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, readFileSync, existsSync, openSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { createServer } from "node:net";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

// A replay transport wrapper calls the same MCP tools a live parent agent calls.
const wrapper = String.raw`
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { readFileSync, writeFileSync } from 'node:fs';
const config = JSON.parse(readFileSync(process.argv[2], 'utf8'));
const child = spawn(process.execPath, [config.replay], {stdio:['pipe','pipe','inherit']});
child.stdout.pipe(process.stdout);
let auth, endpoint, session, seq=0, delegated=false;
async function rpc(method,params) {
 const response=await fetch(endpoint,{method:'POST',headers:{authorization:auth,'content-type':'application/json',accept:'application/json, text/event-stream',...(session?{'mcp-session-id':session}:{})},body:JSON.stringify({jsonrpc:'2.0',id:++seq,method,params})});
 session=response.headers.get('mcp-session-id')??session;
 const text=await response.text();
 const entries=text.startsWith('data:')||text.includes('\ndata:')?text.split('\n').filter(x=>x.startsWith('data:')).map(x=>JSON.parse(x.slice(5))):[JSON.parse(text)];
 const envelope=entries.find(x=>x.id===seq);
 if(envelope?.error) throw Error(JSON.stringify(envelope.error));
 return envelope?.result;
}
for await(const line of createInterface({input:process.stdin})) {
 const msg=JSON.parse(line);
 if(msg.method==='session/new'||msg.method==='session/load') {
  const server=msg.params.mcpServers.find(x=>x.name==='t3-code');
  const env=Object.fromEntries(server.env.map(x=>[x.name,x.value]));
  auth=env.T3_ACP_MCP_AUTHORIZATION; endpoint=env.T3_ACP_MCP_ENDPOINT;
 }
 if(msg.method==='session/prompt'&&!delegated) {
  delegated=true;
  await rpc('initialize',{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'scenario-replay',version:'1'}});
  await rpc('tools/call',{name:'orchestrator_capabilities',arguments:{}});
  const tasks=[];
  for(const title of ['Check the documentation','Check the examples']) {
   const result=await rpc('tools/call',{name:'delegate_task',arguments:{task:'Reply with a short confirmation.',title,target:{environmentId:config.environmentId,projectId:config.projectId,providerInstanceId:'devReplay',model:'multi-turn'}}});
   if(result.isError) throw Error(JSON.stringify(result));
   tasks.push(result.structuredContent);
  }
  writeFileSync(config.done,JSON.stringify(tasks));
 }
 child.stdin.write(line+'\n');
}
child.stdin.end();
`;

const port = () => new Promise<number>((resolve) => {
 const server=createServer(); server.listen(0,'127.0.0.1',()=>{const p=(server.address() as {port:number}).port;server.close(()=>resolve(p));});
});
const cli = (home:string,args:string[]) => execFileSync(process.execPath,["apps/server/src/bin.ts",...args,"--base-dir",home],{cwd:APP_DIR,env:{...process.env,T3CODE_DEV_SEED:'0'},encoding:'utf8',timeout:120000});
const waitFor = async (read:()=>boolean|Promise<boolean>) => {
 const end=Date.now()+120000;
 while(!await read()){if(Date.now()>end)throw Error('Setup did not become ready');await new Promise(r=>setTimeout(r,250));}
};

const navReady = async (screen:any)=>{for(let n=0;;n++){try{await expect(screen.getByRole('navigation','Threads').getByRole('button',/Navigation check/)).toBeVisible();return;}catch(e){if(n>=8)throw e;}}};
test("Archived parents keep linked-environment tasks out of navigation", WEB, async ({t3,app,screen,browser})=>{
 const scratch=join(process.env.PROOF_SCRATCH_ROOT??join(tmpdir(),'linked-task-proof'),String(Date.now())); mkdirSync(scratch,{recursive:true});
 const homeB=join(scratch,'environment-b'); const webPort=await port();
 const log=openSync(join(scratch,'environment-b.log'),'w');
 const serverB=spawn(process.execPath,[join(import.meta.dirname,'start-app.ts'),'web',homeB,'127.0.0.1',String(webPort)],{cwd:APP_DIR,env:{...process.env,T3CODE_DEV_SEED:'0'},stdio:['ignore',log,log]});
 try {
  await waitFor(()=>existsSync(join(homeB,'pairing-path')));
  await waitFor(async()=>{try{return (await fetch(`http://127.0.0.1:${webPort}/.well-known/t3/environment`)).ok}catch{return false}});
  const descriptor=await (await fetch(`http://127.0.0.1:${webPort}/.well-known/t3/environment`)).json();
  const b=makeState(homeB); const projectB=await b.state.project('Remote workspace');
  const projectId=execFileSync('sqlite3',['-readonly',join(homeB,'userdata/statev2.sqlite'),"select project_id from projection_projects where title='Remote workspace'"],{encoding:'utf8'}).trim();
  const pair=()=>JSON.parse(cli(homeB,['auth','pairing','create','--json'])).credential;
  cli(T3_HOME,['environment','link',`http://127.0.0.1:${webPort}`,'--pairing-code',pair()]);
  const project=await t3.project('Parent workspace');
  const warm=await t3.thread({project,title:'Navigation check',messages:['Ready for the sidebar check.']});
  await t3.open(warm);
  await navReady(screen);
  const wrapperPath=join(scratch,'replay-with-tasks.mjs'); writeFileSync(wrapperPath,wrapper);
  const configPath=join(scratch,'replay-config.json'); const done=join(scratch,'delegated.json');
  writeFileSync(configPath,JSON.stringify({replay:join(APP_DIR,'apps/server/scripts/dev-replay-agent.ts'),environmentId:descriptor.environmentId,projectId,done}));
  await browser.evaluate(async (input:any)=>{
   const {appAtomRegistry}=await import('/src/rpc/atomRegistry.ts');
   const {runAtomCommand}=await import('/@fs'+input.runtime);
   const {serverEnvironment}=await import('/src/state/server.ts');
   const {primaryEnvironmentIdAtom}=await import('/src/state/primaryEnvironment.ts');
   const {connectPairing}=await import('/src/connection/onboarding.ts');
   const environmentId=appAtomRegistry.get(primaryEnvironmentIdAtom);
   const updated=await runAtomCommand(appAtomRegistry,serverEnvironment.updateSettings,{environmentId,input:{patch:{linkedEnvironmentsEnabled:true,defaultModelSelection:{instanceId:'devReplay',model:'multi-turn'}},providerInstanceMutation:{operation:'upsert',instanceId:'proofReplay',instance:{displayName:'Replay',driver:'acpRegistry',enabled:true,config:{source:'local',commandPath:input.node,commandArgs:[input.wrapper,input.config]}}}}});
   if(updated._tag==='Failure')throw Error('Could not configure replay: '+JSON.stringify(updated));
   const paired=await runAtomCommand(appAtomRegistry,connectPairing,{host:input.host,pairingCode:input.code});
   if(paired._tag==='Failure')throw Error('Could not pair environment B');
  },{runtime:join(APP_DIR,'packages/client-runtime/src/state/runtime.ts'),node:process.execPath,wrapper:wrapperPath,config:configPath,host:`http://localhost:${/serverPort=(\d+)/.exec(readFileSync(join(scratch,'environment-b.log'),'utf8'))![1]}`,code:pair()});
  const started=JSON.parse(cli(T3_HOME,['thread','start',project,'Delegate two small checks to the linked environment.','--title','Review release notes','--provider','proofReplay','--model','default','--wait','--json']));
  await waitFor(()=>existsSync(done));
  const environmentId=readFileSync(join(T3_HOME,'userdata/environment-id'),'utf8').trim();
  const controlId=execFileSync('sqlite3',['-readonly',join(T3_HOME,'userdata/statev2.sqlite'),"select thread_id from orchestration_v2_projection_threads where title='Navigation check'"],{encoding:'utf8'}).trim();
  const openThread=async(id:string)=>{await app.open('/'+environmentId+'/'+encodeURIComponent(id));await navReady(screen);};
  const capture=async(label:string)=>{
   await browser.evaluate(()=>{const style=document.createElement('style');style.textContent='* {caret-color:transparent!important}';document.head.append(style);});
   let previous=await app.screenshot(label+'-settling');
   for(let n=0;n<20;n++){
    await new Promise(resolve=>setTimeout(resolve,500));
    const next=await app.screenshot(label);
    if(readFileSync(previous).equals(readFileSync(next)))return;
    previous=next;
   }
   throw Error('The capture did not settle: '+label);
  };
  await openThread(started.threadId);
  await capture('grouped-before-archive');
  const diag0=await browser.evaluate(async(input:any)=>{
   const {appAtomRegistry}=await import('/src/rpc/atomRegistry.ts');
   const {environmentCatalog}=await import('/src/connection/catalog.ts');
   const {environmentThreadShells}=await import('/src/state/threads.ts');
   const cat=appAtomRegistry.get(environmentCatalog.catalogValueAtom);
   const entries=[...cat.entries].map(([k,v]:any)=>({k,enabled:v.enabled}));
   const b=appAtomRegistry.get(environmentThreadShells.environmentThreadsAtom(input.b)).map((t:any)=>({id:t.id,title:t.title,archivedAt:t.archivedAt,settledAt:t.settledAt,delegatedFrom:t.delegatedFrom}));
   const nav=appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom).map((t:any)=>t.title);
   const under=[...appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom)];
   return JSON.stringify({entries,b,nav,under});
  },{b:descriptor.environmentId});
  writeFileSync(join(scratch,'diag-'+Date.now()+'.json'),diag0);
  // Drive the same command used by the archive menu, through the connected client.
  const changeArchive=async (archive:boolean)=>browser.evaluate(async(input:any)=>{
   const {appAtomRegistry}=await import('/src/rpc/atomRegistry.ts');
   const {runAtomCommand}=await import('/@fs'+input.runtime);
   const {threadEnvironment}=await import('/src/state/threads.ts');
   const {primaryEnvironmentIdAtom}=await import('/src/state/primaryEnvironment.ts');
   const result=await runAtomCommand(appAtomRegistry,input.archive?threadEnvironment.archive:threadEnvironment.unarchive,{environmentId:appAtomRegistry.get(primaryEnvironmentIdAtom),input:{threadId:input.threadId}});
   if(result._tag==='Failure')throw Error('Archive command failed');
  },{archive,threadId:started.threadId,runtime:join(APP_DIR,'packages/client-runtime/src/state/runtime.ts')});
  await openThread(controlId);
  await changeArchive(true);
  await capture('archived-immediate');
  await app.open('/'+environmentId+'/'+encodeURIComponent(controlId));
  await navReady(screen);
  await navReady(screen);
  await capture('archived-after-reload');
  const diag=await browser.evaluate(async(input:any)=>{
   const {appAtomRegistry}=await import('/src/rpc/atomRegistry.ts');
   const {environmentCatalog}=await import('/src/connection/catalog.ts');
   const {environmentThreadShells}=await import('/src/state/threads.ts');
   const cat=appAtomRegistry.get(environmentCatalog.catalogValueAtom);
   const entries=[...cat.entries].map(([k,v]:any)=>({k,enabled:v.enabled}));
   const b=appAtomRegistry.get(environmentThreadShells.environmentThreadsAtom(input.b)).map((t:any)=>({id:t.id,title:t.title,archivedAt:t.archivedAt,settledAt:t.settledAt,delegatedFrom:t.delegatedFrom}));
   const nav=appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom).map((t:any)=>t.title);
   const under=[...appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom)];
   return JSON.stringify({entries,b,nav,under});
  },{b:descriptor.environmentId});
  writeFileSync(join(scratch,'diag-'+Date.now()+'.json'),diag);
  await expect.soft(screen.getByRole('navigation','Threads').getByRole('button',/^Check the documentation,/)).toBeHidden();
  await expect.soft(screen.getByRole('navigation','Threads').getByRole('button',/^Check the examples,/)).toBeHidden();
  await changeArchive(false);
  await openThread(started.threadId);
  await capture('unarchived-grouped');
 } finally {serverB.kill('SIGTERM');await new Promise<void>(resolve=>{if(serverB.exitCode!==null)resolve();else serverB.once('exit',()=>resolve());});}
});
