// @effect-diagnostics nodeBuiltinImport:off -- A wrapper forwards the real replay agent's ACP stream.
import * as FS from "node:fs/promises";
import { execFileSync } from "node:child_process";
import * as Path from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";

const wrapper = `
import { spawn } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
const child = spawn(process.execPath, [process.argv[2]], {stdio:['pipe','pipe','inherit']});
child.stdout.pipe(process.stdout);
for await (const line of createInterface({input:process.stdin})) {
 const msg=JSON.parse(line);
 if(msg.method==='session/new' || msg.method==='session/load') writeFileSync(process.argv[3],JSON.stringify(msg.params.mcpServers));
 child.stdin.write(line+'\\n');
}
child.stdin.end();
`;

test("Stopping a parent stops its remote delegated task", WEB, async ({ t3, app, screen, browser }) => {
 const project = await t3.project("delegation-demo", {"replay-wrapper.mjs": wrapper});
 const origin = app.baseUrl ?? "";
 const startedAt = Date.now();
 const server = startSecondServer(origin);
 void server.ready.catch(()=>{});
 try {
  let host = "";
  for(let attempt=0;attempt<300;attempt++){
   const state=await FS.readFile(Path.join(SECOND_HOME,"userdata/server-runtime.json"),"utf8").then(JSON.parse).catch(()=>null);
   if(state && Date.parse(state.startedAt)>=startedAt){host=state.origin;break;}
   await new Promise(resolve=>setTimeout(resolve,100));
  }
  if(!host) throw new Error("Second server did not start");
  const remote = makeState(SECOND_HOME);
  const remoteProject = await remote.state.project("delegation-demo");
  for (const repo of [project,remoteProject]) execFileSync("git",["remote","add","origin","https://example.invalid/scenario/delegation-demo.git"],{cwd:repo});
  const token = (await runPromise(remote.cli(["auth","session","issue","--token-only"]))).stdout.trim();
  const remoteProjects = await fetch(`${host}/api/projects`,{headers:{authorization:`Bearer ${token}`}}).then(r=>r.json());
  const remoteProjectId = remoteProjects.projects.find((p:any)=>p.workspaceRoot===remoteProject).id;
  const remoteEnv = await runPromise(environmentId(host));
  const instanceId = ProviderInstanceId.make("scenario-replay-parent");
  const credentialsFile = Path.join(project,"mcp-session.json");
  await runPromise(Effect.gen(function* () {
   const primary = yield* rpcClient(T3_HOME, origin);
   const secondary = yield* rpcClient(SECOND_HOME, host);
   for(const client of [primary,secondary]) yield* client["server.updateSettings"]({patch:{linkedEnvironmentsEnabled:true}});
   const pairing = JSON.parse((yield* remote.cli(["auth","pairing","create","--json"])).stdout);
   yield* primary["peerLinks.link"]({url:host,pairingCode:pairing.credential,access:"full-access"});
   yield* primary["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId,instance:{driver:ProviderDriverKind.make("acpRegistry"),displayName:"Replay parent",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[Path.join(project,"replay-wrapper.mjs"),Path.join(APP_DIR,"apps/server/scripts/dev-replay-agent.ts"),credentialsFile]}}}});
  }).pipe(Effect.scoped));
  const primary = makeState(T3_HOME);
  const started = await runPromise(primary.cli(["thread","start",project,"Delegate a remote task and wait.","--title","Parent with remote task","--provider",instanceId,"--model","question","--wait","--json"],[0,2]));
  const {threadId} = JSON.parse(started.stdout);
  const configs = JSON.parse(await FS.readFile(credentialsFile,"utf8"));
  const config = configs.find((s:any)=>s.name==='t3-code');
  const endpoint = config.url ?? config.env.find((v:any)=>v.name==='T3_ACP_MCP_ENDPOINT').value;
  const authorization = config.headers?.find((v:any)=>v.name.toLowerCase()==='authorization')?.value ?? config.env.find((v:any)=>v.name==='T3_ACP_MCP_AUTHORIZATION').value;
  const delegated:any = await runPromise(Effect.gen(function*(){
   const mcp = yield* mcpToolSession({endpoint,authorization,clientName:"scenario"});
   return yield* mcp.call("delegate_task",{task:"Wait for an answer from the user.",title:"Remote delegated task",mode:"async",target:{environmentId:remoteEnv,projectId:remoteProjectId,providerInstanceId:"devReplay",model:"question"}});
  }).pipe(Effect.scoped));
  const task = delegated.structuredContent ?? JSON.parse(delegated.content.find((c:any)=>c.type==='text').text);
  if(!task.remoteChild?.threadId) throw new Error('Remote delegation did not launch: '+JSON.stringify(delegated));
  const childId = task.remoteChild.threadId;
  await t3.open({threadId});
  await browser.locator('button[aria-label="Stop generation"]').waitFor();
  await app.screenshot("remote-task-before-stop");
  await screen.getByRole("button","Stop generation").tap();
  try {
  await expect.poll(async()=>{
   const shown = await runPromise(remote.cli(["thread","show",childId,"--json"]));
   return JSON.parse(shown.stdout).thread.status;
  },{timeout:30000}).toBe("interrupted");
  } finally {
   const via = await runPromise(environmentId(origin));
   await t3.open(`/linked/${via}/${remoteEnv}/${childId}`);
   await screen.getByText("Wait for an answer from the user.",{exact:false}).first().waitFor({timeout:60000});
   await app.screenshot("remote-task-after-stop");
  }
 } finally {await server.stop();}
});
