import { expect } from "e2e";
import { readFile, writeFile, unlink } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

test("A resumed delegated follow-up shows Waiting in its parent", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("Delegated waiting proof");
  const parent = await t3.thread({project, title: "Parent task status", messages:["Ask for a preference"], model:"question"});
  const {origin} = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const token = execFileSync(process.execPath, ["apps/server/src/bin.ts", "auth", "session", "issue", "--token-only", "--label", "proof driver", "--base-dir", T3_HOME], {cwd:APP_DIR, encoding:"utf8"}).trim();
  const ticket = await fetch(`${origin}/api/auth/websocket-ticket`, {method:"POST", headers:{authorization:`Bearer ${token}`}}).then(r=>r.json());
  const ws = new WebSocket(`${origin.replace('http','ws')}/ws?orchestrationProtocol=2&wsTicket=${encodeURIComponent(ticket.ticket)}`);
  await new Promise<void>((resolve,reject)=>{ws.onopen=()=>resolve(); ws.onerror=()=>reject(new Error("Driver socket failed"));});
  let id = 0;
  const pending = new Map<string, {resolve:(v:any)=>void,reject:(e:any)=>void}>();
  ws.onmessage = event => {
    const msg = JSON.parse(String(event.data));
    for (const frame of Array.isArray(msg)?msg:[msg]) {
      if (frame._tag === "Ping") {ws.send(JSON.stringify({_tag:"Pong"})); continue;}
      if (frame._tag !== "Exit") continue;
      const p = pending.get(String(frame.requestId));
      if (!p) continue;
      pending.delete(String(frame.requestId));
      frame.exit._tag === "Success" ? p.resolve(frame.exit.value) : p.reject(new Error(JSON.stringify(frame.exit)));
    }
  };
  const rpc = (tag:string,payload:any) => new Promise<any>((resolve,reject)=>{
    const key=String(++id); pending.set(key,{resolve,reject});
    ws.send(JSON.stringify({_tag:"Request",id:key,tag,payload,headers:[]}));
  });
  const dispatch = (command:any) => rpc("orchestration.dispatchCommand", {commandId:crypto.randomUUID(),createdBy:"user",creationSource:"web",...command});
  const projection = (threadId:string) => rpc("orchestration.getThreadProjection",{threadId});
  const until = async (label:string, get:()=>Promise<any>, predicate:(v:any)=>boolean) => {
    for(let i=0;i<200;i++) {const p=await get();if(predicate(p)) return p;await new Promise(r=>setTimeout(r,100));}
    throw new Error(`STEP_TIMEOUT: ${label}`);
  };
  try {
    const p = await projection(parent.threadId);
    const run = p.runs.at(-1);
    await dispatch({type:"delegated_task.request", parentThreadId:parent.threadId,parentRunId:run.id,parentNodeId:run.rootNodeId,task:"Complete the initial task",title:"Review follow-up",modelSelection:{instanceId:"devReplay",model:"multi-turn"},runtimeMode:"approval-required",interactionMode:"default",completionWake:"settled_only"});
    const done = await until("initial child completed",()=>projection(parent.threadId),p=>p.subagents.some((s:any)=>s.result!==null));
    const childId=done.subagents[0].childThreadId;
    await t3.open(parent);
    await screen.getByRole("textbox", "Message Parent task status").textContent();

    const send = (text:string) => dispatch({type:"message.dispatch",threadId:childId,messageId:crypto.randomUUID(),text,attachments:[],dispatchMode:{type:"queue_after_active"}});
    await send("Active follow-up: ask for a preference");
    await until("active follow-up running",()=>projection(childId),p=>p.runs.at(-1).status==="running");
    await send("Queued follow-up: ask for a preference");
    const queued = await projection(childId);
    const followup=queued.runs.at(-1);
    if(followup.status!=="queued") throw new Error(`Expected queued setup, got ${followup.status}`);
    await dispatch({type:"thread.stop",threadId:childId});
    await until("parent follow-up idle",()=>projection(parent.threadId),p=>p.subagents.find((s:any)=>s.id===followup.delegatedTaskId)?.status==="idle");
    await screen.getByRole("button", "3 subagents").tap();
    await screen.getByRole("button", "Open Review follow-up").last().textContent();
    await app.screenshot("paused-follow-up");
    // Hold real checkpoint Git I/O so the genuine waiting run remains visible for capture.
    await writeFile(`${project}/.git/hold-checkpoint.sh`, '#!/bin/sh\nfor i in $(seq 1 600); do test -f .git/proof-gate || break; sleep 0.1; done\ncat\n', {mode:0o755});
    await writeFile(`${project}/.git/proof-gate`, 'hold');
    await writeFile(`${project}/.gitattributes`, '*.proof filter=proof\n');
    await writeFile(`${project}/checkpoint.proof`, 'Synthetic checkpoint content\n');
    execFileSync('git',['config','filter.proof.clean','.git/hold-checkpoint.sh'],{cwd:project});
    await dispatch({type:"queue.resume",threadId:childId});
    await until("resumed child waiting",()=>projection(childId),p=>p.runs.find((r:any)=>r.id===followup.id)?.status==="waiting");


    const final = await projection(parent.threadId);
    const status=final.subagents.find((s:any)=>s.id===followup.delegatedTaskId)?.status;
    console.log(`Follow-up parent subagent=${status}; node=${final.nodes.find((n:any)=>n.id===followup.delegatedTaskId)?.status}`);
    await until("task card reflects server projection", () => screen.getByRole("button", "Open Review follow-up").last().getAttribute("aria-description"), value=>value?.toLowerCase()===status);
    await app.screenshot("parent-after-child-waits");
    await expect(status).toBe("waiting");
    await expect(final.nodes.find((n:any)=>n.id===followup.delegatedTaskId)?.status).toBe("waiting");
    await expect(screen.getByRole("button", "Open Review follow-up").last()).toHaveAttribute("aria-description", "Waiting");
  } finally {await unlink(`${project}/.git/proof-gate`).catch(()=>{}); ws.close();}
});
