import { expect } from "e2e";
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { test, WEB, makeState, runPromise, environmentId } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

const pause = (ms: number) => new Promise(r => setTimeout(r, ms));
// Use a 900_000 ms timeout in scripts/e2e.config.ts for the delayed recheck.
const scratch = process.env.T3_PROOF_SCRATCH ?? "/tmp/t3-launch-proof";
mkdirSync(scratch, {recursive: true});
const db = `${T3_HOME}/userdata/statev2.sqlite`;
const query = (sql: string) => JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", db, sql], { encoding: "utf8" }) || "[]");
async function until<T>(fn: () => T | undefined, ms = 30000): Promise<T> {
 const end = Date.now()+ms;
 while(Date.now()<end) { const v=fn(); if(v !== undefined) return v; await pause(25); }
 throw new Error("Timed out waiting for real server milestone");
}
function parse(text: string) {
 if(text.trim().startsWith("{")) return JSON.parse(text);
 const lines=text.split("\n").filter(l=>l.startsWith("data: "));
 return JSON.parse(lines.at(-1)!.slice(6));
}

test("Committed launches and cancelled wait delegations finish", WEB, async ({t3,app,screen}) => {
 // Only the free model fixture is instrumented: expose its own MCP credentials locally,
 // and keep the parent turn alive while requests are cancelled. Server code is unchanged.
 const fixture=`${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
 let source=readFileSync(fixture,"utf8");
 source=source.replace('const params = message.params ?? {};', `const params = message.params ?? {};
 if (message.method === "session/new" || message.method === "session/load") {
   NodeFS.writeFileSync(String(params.cwd)+"/evidence-session.json", JSON.stringify({params,env:{endpoint:process.env.T3_ACP_MCP_ENDPOINT,authorization:process.env.T3_ACP_MCP_AUTHORIZATION}}));
 }
 if (message.method === "session/prompt") {
   const cwd=sessions.get(String(params.sessionId))?.cwd;
   if(cwd) {
     NodeFS.appendFileSync(cwd+"/evidence-prompts.jsonl", JSON.stringify(params)+"\\n");
     if(JSON.stringify(params.prompt).includes("Wait completion marker")) await new Promise(r=>setTimeout(r,3000));
     if(JSON.stringify(params.prompt).includes("EVIDENCE_PARENT_HOLD")) {
       while(!NodeFS.existsSync(cwd+"/evidence-release")) await new Promise(r=>setTimeout(r,50));
     }
   }
 }`);
 writeFileSync(fixture,source);
 const project=await t3.project("Cancellation proof");
 const state=makeState(T3_HOME);
 const started=await runPromise(state.cli(["thread","start",project,"EVIDENCE_PARENT_HOLD", "--title","Cancellation parent","--provider","devReplay","--model","multi-turn","--json"]));
 const parent=JSON.parse(started.stdout);
 await until(()=>existsSync(`${project}/evidence-session.json`) ? true:undefined);
 const setup=JSON.parse(readFileSync(`${project}/evidence-session.json`,"utf8"));
 const env=Object.fromEntries((setup.params.mcpServers?.[0]?.env ?? []).map((e:any)=>[e.name,e.value]));
 const endpoint=setup.env.endpoint ?? env.T3_ACP_MCP_ENDPOINT;
 const authorization=setup.env.authorization ?? env.T3_ACP_MCP_AUTHORIZATION;
 if(!endpoint || !authorization) throw new Error("Replay MCP configuration unavailable");
 const headers:any={accept:"application/json, text/event-stream","content-type":"application/json",authorization};
 const post=async(body:any) => {const r=await fetch(endpoint,{method:"POST",headers,body:JSON.stringify({jsonrpc:"2.0",...body})}); if(!r.ok) throw new Error(`MCP HTTP ${r.status}: ${await r.text()}`); return r;};
 const init=await post({id:1,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"cancellation-proof",version:"1"}}});
 headers["mcp-session-id"]=init.headers.get("mcp-session-id"); headers["mcp-protocol-version"]="2025-06-18";
 await init.text(); await post({method:"notifications/initialized"});
 let id=2;
 const call=async(name:string,args:any,cancelMs?:number) => {
  const requestId=id++;
  const pending=post({id:requestId,method:"tools/call",params:{name,arguments:args}}).then(async r=>parse(await r.text())).catch(e=>({error:String(e)}));
  if(cancelMs!==undefined) {await pause(cancelMs); await post({method:"notifications/cancelled",params:{requestId,reason:"Caller interrupted"}});}
  return await pending;
 };
 await t3.open(parent);
 const launch=(title:string)=>({title,message:"Run the replay",workspaceStrategy:{type:"worktree",baseRef:"main",startFromOrigin:false},modelSelection:{instanceId:"devReplay",model:"multi-turn"}});
 const control=await call("t3_thread_launch",launch("Control launch"));

 if(control.error || control.result?.isError) throw new Error("Control launch failed: "+JSON.stringify(control));
 await until(()=>query("select status from orchestration_v2_projection_runs where thread_id='"+control.result.structuredContent.threadId+"'")[0]?.status === "completed" ? true:undefined);
 const replies:any[]=[];
 for(let round=0;round<2;round++) {
  for(const tool of ["t3_thread_launch","delegate_task"]) {
   for(let i=0;i<=20;i++) {
    const title=`${tool === "delegate_task" ? "Delegate" : "Launch"} ${round}-${String(i).padStart(2,"0")} (${i*3} ms)`;
    const args=tool === "t3_thread_launch" ? launch(title) : {title,task:"Run the replay",isolation:"worktree",mode:"wait",target:{providerInstanceId:"devReplay",model:"multi-turn"}};
    replies.push({tool,title,cancelMs:i*3,response:await call(tool,{...args,clientRequestId:title},i*3)});
   }
   console.log("Sweep complete",round,tool);
  }
 }
 // Cancel as soon as the real database exposes the committed run. This makes
 // each matched request exist on both sides even when pre-dispatch timing differs.
 for(const tool of ["t3_thread_launch","delegate_task"]) {
  for(let i=0;i<12;i++) {
   const title=`${tool === "delegate_task" ? "Delegate" : "Launch"} committed-${String(i).padStart(2,"0")}`;
   const args=tool === "t3_thread_launch" ? launch(title) : {title,task:"Run the replay",isolation:"worktree",mode:"wait",target:{providerInstanceId:"devReplay",model:"multi-turn"}};
   const requestId=id++;
   let finished=false;
   const pending=post({id:requestId,method:"tools/call",params:{name:tool,arguments:{...args,clientRequestId:title}}}).then(async r=>parse(await r.text())).catch(e=>({error:String(e)})).finally(()=>{finished=true;});
   const deadline=Date.now()+10000;
   let committed=false;
   while(Date.now()<deadline) {
    committed=query("select thread_id from orchestration_v2_projection_threads where title='"+title+"'").length>0;
    if(committed || finished) break;
    await pause(1);
   }
   if(!committed) throw new Error("Committed cancellation control failed: "+title+JSON.stringify(await pending));
   await post({method:"notifications/cancelled",params:{requestId,reason:"Caller interrupted after commit"}});
   replies.push({tool,title,committed:true,response:await pending});
  }
  console.log("Committed cancellation sweep complete",tool);
 }
 const waitRequestId=id++;
 const waitPending=post({id:waitRequestId,method:"tools/call",params:{name:"delegate_task",arguments:{title:"Wait completion marker",task:"Wait completion marker",isolation:"worktree",mode:"wait",target:{providerInstanceId:"devReplay",model:"multi-turn"},clientRequestId:"wait-delivery"}}}).then(async r=>parse(await r.text())).catch(e=>({error:String(e)}));
 await until(()=>query("select r.status from orchestration_v2_projection_threads t join orchestration_v2_projection_runs r using(thread_id) where t.title='Wait completion marker'").some((r:any)=>r.status === "running") ? true:undefined,60000);
 await pause(200);
 await post({method:"notifications/cancelled",params:{requestId:waitRequestId,reason:"Caller interrupted while waiting for running child"}});
 const waitReply=await waitPending;
 replies.push({tool:"delegate_task",title:"Wait completion marker",cancelAfterRunningMs:200,response:waitReply});
 writeFileSync(`${project}/evidence-release`,"release");
 const runs=()=>query("select t.title,t.thread_id,r.status,r.requested_at from orchestration_v2_projection_threads t join orchestration_v2_projection_runs r using(thread_id) where t.title like 'Launch %' or t.title like 'Delegate %' order by t.title");
 await pause(20000);
 const early=runs();
 const sha=execFileSync("git",["rev-parse","HEAD"],{cwd:APP_DIR,encoding:"utf8"}).trim();
 const base=sha === "414a068f67f0b0d3c478b1f18e63c39acf9f89ed";
 const selectionFile=`${scratch}/matching-titles.json`;
 const selected=base ? {
  launch:early.find((r:any)=>r.title.startsWith("Launch committed-") && r.status === "preparing")?.title ?? "Launch committed-00",
  delegate:early.find((r:any)=>r.title.startsWith("Delegate committed-") && r.status === "preparing")?.title ?? "Delegate committed-00"
 } : JSON.parse(readFileSync(selectionFile,"utf8"));
 if(base) writeFileSync(selectionFile,JSON.stringify(selected));
 const capture=async(kind:string,label:string)=>{
  const row=runs().find((r:any)=>r.title === selected[kind]);
  if(!row) throw new Error("Matching capture thread was not created: "+selected[kind]);
  const envId=await runPromise(environmentId(app.baseUrl ?? ""));
  await t3.open(`/${envId}/${encodeURIComponent(row.thread_id)}`);
  await pause(3500);
  await app.screenshot(label);
 };
 await capture("launch","cancelled-launch-early");
 await capture("delegate","cancelled-delegate-early");
 // The reported failure survives five minutes after other children have completed.
 const deadline=Date.now()+310000;
 let nextProgress=Date.now()+30000;
 while(Date.now()<deadline) { await pause(Math.min(1000,deadline-Date.now())); if(Date.now()>=nextProgress) { console.log("Delayed recheck in",Math.ceil((deadline-Date.now())/1000),"seconds"); nextProgress+=30000; } }
 await capture("launch","cancelled-launch-after-five-minutes");
 await capture("delegate","cancelled-delegate-after-five-minutes");
 await t3.open(parent); await pause(3500); await app.screenshot("parent-completion-delivery");
 const final=runs();
 const tasks=query("select payload_json from orchestration_v2_projection_subagents").map((r:any)=>JSON.parse(r.payload_json));
 const preparing=final.filter((r:any)=>r.status === "preparing");
 const waitTask=tasks.find((t:any)=>t.title === "Wait completion marker" || t.task === "Wait completion marker");
 const summary={sha,selected,early,final,preparing,waitTask,tasks,replies};
 writeFileSync(`${scratch}/${base ? "base" : "head"}-observations.json`,JSON.stringify(summary,null,2));
 console.log("OBSERVED",JSON.stringify({sha,selected,preparing:preparing.map((r:any)=>r.title),waitTask,tasks:tasks.map((t:any)=>({title:t.title,status:t.status,wake:t.completionWake,delivery:t.completionDelivery}))}));
 expect({preparing:preparing.map((r:any)=>r.title),waitStatus:waitTask?.status,waitDelivery:waitTask?.completionDelivery?.state}).toEqual({preparing:[],waitStatus:"completed",waitDelivery:"delivered"});
});
