import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { randomUUID } from "node:crypto";
import { CommandId, MessageId, ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const ACP = `
import { createInterface } from "node:readline";
import { watch, existsSync } from "node:fs";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
const sessionId = randomUUID();
const send = (message) => process.stdout.write(JSON.stringify({jsonrpc:"2.0", ...message}) + "\\n");
let promptId, watcher, cwd;
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if(method === "session/cancel" && promptId !== undefined) {
  watcher?.close(); send({id:promptId,result:{stopReason:"cancelled"}}); promptId=undefined;
 }
 if(id === undefined || method === undefined) continue;
 if(method === "initialize") send({id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[],agentInfo:{name:"Delegation replay",version:"1"}}});
 else if(method === "session/new" || method === "session/load") { cwd=params.cwd; send({id,result:{sessionId}}); }
 else if(method === "session/prompt") {
  promptId=id;
  const text=JSON.stringify(params.prompt);
  const parent=text.includes("Delegate the work");
  send({method:"session/update",params:{sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:parent?"Parent is delegating the child task.":"Child is working. Waiting for your next instruction."}}}});
  if(parent) {
   const finish=()=>{if(existsSync(join(cwd,"finish-parent"))) {watcher?.close();send({id,result:{stopReason:"end_turn"}});promptId=undefined;}};
   watcher=watch(cwd,finish);finish();
  }
 } else send({id,result:{}});
}
`;

test("Stopping a delegated child with queued work does not wake its parent as interrupted", WEB, async ({t3,app,screen,browser}) => {
 const project=await t3.project("delegation-demo", {"replay-agent.mjs":ACP});
 const parent=await t3.thread({project,title:"Parent delegation",messages:["Prepare the delegation"]});
 const instanceId=ProviderInstanceId.make("delegation-replay");
 const modelSelection={instanceId,model:"default"};
 const rpc = async (action: (client: any)=>Effect.Effect<any, any, any>) => runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME,app.baseUrl ?? "");
  return yield* action(client);
 }).pipe(Effect.scoped) as any);
 const dispatch=(command:any)=>rpc(client=>client["orchestration.dispatchCommand"]({...command,commandId:CommandId.make(randomUUID())}));
 const read=(id:string)=>rpc(client=>client["orchestration.getThreadProjection"]({threadId:ThreadId.make(id)}));
 await rpc(client=>client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId,instance:{driver:ProviderDriverKind.make("acpRegistry"),displayName:"Delegation replay",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[Path.join(project,"replay-agent.mjs")]}}}}));
 await dispatch({type:"provider.switch",threadId:parent.threadId,modelSelection});
 await t3.open(parent);
 await dispatch({type:"message.dispatch",threadId:parent.threadId,messageId:MessageId.make(randomUUID()),text:"Delegate the work",attachments:[],dispatchMode:{type:"start_immediately"},createdBy:"user",creationSource:"web"});
 await screen.getByText("Parent is delegating the child task.",{exact:false}).waitFor();
 const running=await read(parent.threadId);
 const run=running.runs.at(-1);
 await dispatch({type:"delegated_task.request",parentThreadId:parent.threadId,parentRunId:run.id,parentNodeId:run.rootNodeId,task:"Do the child work",title:"Delegated child",modelSelection,runtimeMode:"full-access",interactionMode:"default",completionWake:"always",createdBy:"agent",creationSource:"mcp"});
 const delegated=await read(parent.threadId);
 const childId=delegated.subagents.at(-1).childThreadId;
 await FS.writeFile(Path.join(project,"finish-parent"),"done");
 await screen.getByRole("button","Stop generation").waitFor({state:"hidden"});
 await t3.open({threadId:childId});
 await screen.getByText("Child is working. Waiting for your next instruction.",{exact:false}).waitFor();
 await dispatch({type:"message.dispatch",threadId:childId,messageId:MessageId.make(randomUUID()),text:"Actually, do it this way",attachments:[],dispatchMode:{type:"queue_after_active"},createdBy:"user",creationSource:"web"});
 await screen.getByText("Actually, do it this way",{exact:false}).first().waitFor();
 await app.screenshot("child-follow-up-queued");
 await screen.getByRole("button","Stop generation").tap();
 await screen.getByRole("button","Stop generation").waitFor({state:"hidden"});
 await app.screenshot("child-stopped-with-held-message");
 await t3.open(parent);
 await screen.getByText("Parent is delegating the child task.",{exact:false}).waitFor();
 // Let the visible task row finish updating before capturing the parent.
 await browser.locator('[data-chat-composer-form="true"]').waitFor();
 await app.screenshot("parent-after-child-stop");
 await expect(screen.getByText("Child task ended with status interrupted",{exact:false})).toBeHidden();
 const final=await read(parent.threadId);
 await expect(final.messages.filter((message:any)=>message.delegatedCompletion).map((message:any)=>message.text)).toEqual([]);
});
