// @effect-diagnostics nodeBuiltinImport:off -- Scratch replay agent and synchronization files.
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const commands = [
  'bash -c -- "printf ok"',
  'sh -c -- "printf ok"',
  'bash -lc -- "printf ok"',
  'bash -c -- "sleep 30; printf ok"',
  'bash -lc -- "sleep 30; printf ok"',
  'bash -c "sleep 30; printf ok"',
  'bash -c -- "printf ok" arg0',
  'bash -c --',
];
const replay = (signal: string) => `
import { createInterface } from "node:readline";
import { watch, existsSync } from "node:fs";
const sessionId = "shell-replay";
const commands = ${JSON.stringify(commands)};
const send = x => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...x }) + "\\n");
const update = x => send({ method: "session/update", params: { sessionId, update: x } });
const wait = () => new Promise(resolve => {
 const watcher = watch(${JSON.stringify(signal)}, (_, name) => { if(name === "finish") { watcher.close(); resolve(); } });
 if(existsSync(${JSON.stringify(signal + "/finish")})) { watcher.close(); resolve(); }
});
for await (const line of createInterface({input: process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if(id === undefined) continue;
 if(method === "initialize") send({id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[]}});
 else if(method === "session/new") send({id,result:{sessionId}});
 else if(method === "session/prompt") {
  const i = Number(JSON.stringify(params).match(/CASE_INDEX=(\\d+)/)?.[1] ?? "0");
  const command = commands[i];
  update({sessionUpdate:"tool_call",toolCallId:"shell-"+i,kind:"execute",title:command,status:"in_progress",rawInput:{command}});
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Shell replay ready " + i}});
  await wait();
  update({sessionUpdate:"tool_call_update",toolCallId:"shell-"+i,status:"completed",rawOutput:"ok"});
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:" Replay finished."}});
  send({id,result:{stopReason:"end_turn"}});
 } else send({id,error:{code:-32601,message:"Method not found"}});
}
`;

test("Shell option terminators show the executable and unwrap simple scripts", WEB, async ({t3,app,screen,browser}) => {
 const project = await t3.project("shell-demo");
 const signal = await fs.mkdtemp(path.join(T3_HOME,"shell-signals-"));
 const script = path.join(project,"shell-replay.mjs");
 await fs.writeFile(script,replay(signal));
 const settingsPath = path.join(T3_HOME,"userdata/settings.json");
 const original = await fs.readFile(settingsPath,"utf8");
 const settings = JSON.parse(original);
 settings.providerInstances["shell-replay"] = {driver:"acpRegistry",displayName:"Shell replay",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[script]}};
 try {
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME,app.baseUrl ?? "");
   yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some(provider => provider.instanceId === "shell-replay")),Stream.runHead);
  }).pipe(Effect.scoped));
  const {cli} = makeState(T3_HOME);
  const observations: {active:string; displayed:boolean}[] = [];
  const titles = ["bash -c with terminator", "sh -c with terminator", "bash -lc with terminator", "bash -c running", "bash -lc running", "Control without terminator", "Positional argument retained", "Missing script"];
  for(const [i,command] of commands.entries()) {
   if(i > 0) await fs.unlink(path.join(signal,"finish"));
   const started = await runPromise(cli(["thread","start",project,"CASE_INDEX="+i,"--title",titles[i],"--provider","shell-replay","--model","default","--json"]));
   await t3.open({threadId:JSON.parse(started.stdout).threadId});
   await screen.getByText("Shell replay ready " + i,{exact:true}).waitFor({timeout:60000});
   await app.screenshot("case-"+i+"-active-label");
   const active = await browser.evaluate(() => document.body.innerText);
   await fs.writeFile(path.join(signal,"finish"),"");
   await screen.getByRole("button","Stop generation").waitFor({state:"hidden"});
   await screen.getByRole("button","Worked for",{exact:false}).tap();
   await app.screenshot("case-"+i+"-completed-command");
   const expected = i < 3 ? "printf ok" : (i >= 3 && i <= 5) ? "sleep 30; printf ok" : command;
   observations.push({active, displayed:(await screen.getByText(expected,{exact:true}).count()) > 0});
  }
  for(const [i,observation] of observations.entries()) {
   const label = i < 3 || i === 6 ? "Running printf" : i === 7 ? "Running command" : "Running sleep";
   expect(observation.active, titles[i]+" executable label").toContain(label);
   expect(observation.displayed, titles[i]+" displayed command").toBe(true);
  }
 } finally { await fs.writeFile(path.join(signal,"finish"),""); await fs.writeFile(settingsPath,original); }
});
