import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

test("Self-settle survives a queued message promoted to steer", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Self-settle demo");
  // The fixture is an ACP replay agent with a real authenticated MCP call, not a simulated settle result.
  const source = await readFile(join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8");
  const agentPath = join(T3_HOME, "settle-replay.ts");
  const gate = join(project, "finish-turn");
  const custom = source
    .replace('const sessions = new Map<', 'let mcp: any;\n  const sessions = new Map<')
    .replace('agentCapabilities: {', 'agentCapabilities: { mcpCapabilities: { http: true },')
    .replace('const cwd = typeof params.cwd', 'mcp = (params.mcpServers as any[])?.find(s => s.name === "t3-code");\n        const cwd = typeof params.cwd')
    .replace('const turns = loadTurns(session.model);', `
        const update = (text: string) => send({method: "session/update", params: {sessionId, update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text}}}});
        update("Work is running. Queue the settle instruction, then press Send now.\\n");
        while (!NodeFS.existsSync(${JSON.stringify(gate)})) await new Promise(r => setTimeout(r, 100));
        const bridgeEnv = Object.fromEntries((mcp?.env ?? []).map((e: any) => [e.name, e.value]));
        const endpoint = mcp?.url ?? bridgeEnv.T3_ACP_MCP_ENDPOINT ?? process.env.T3_ACP_MCP_ENDPOINT;
        const authorization = bridgeEnv.T3_ACP_MCP_AUTHORIZATION ?? process.env.T3_ACP_MCP_AUTHORIZATION;
        if (!endpoint) throw new Error("No MCP endpoint supplied");
        const headers = mcp?.type === "http" ? Object.fromEntries((mcp.headers ?? []).map((h: any) => [h.name, h.value])) : {Authorization: authorization};
        const commonHeaders = {...headers, "Content-Type": "application/json", Accept: "application/json, text/event-stream"};
        const initialized = await fetch(endpoint, {method: "POST", headers: commonHeaders, body: JSON.stringify({jsonrpc: "2.0", id: 0, method: "initialize", params: {protocolVersion: "2025-03-26", capabilities: {}, clientInfo: {name: "settle-replay", version: "1"}}})});
        await initialized.text();
        headers["MCP-Session-Id"] = initialized.headers.get("mcp-session-id");
        await fetch(endpoint, {method: "POST", headers: {...commonHeaders, ...headers}, body: JSON.stringify({jsonrpc: "2.0", method: "notifications/initialized"})});
        const response = await fetch(endpoint, {method: "POST", headers: {...headers, "Content-Type": "application/json", Accept: "application/json, text/event-stream"}, body: JSON.stringify({jsonrpc: "2.0", id: 1, method: "tools/call", params: {name: "t3_thread_organize", arguments: {action: "settle"}}})});
        const body = await response.text();
        if (!body.includes('settlesWhenTurnEnds')) throw new Error("Self-settle failed: " + body);
        NodeFS.writeFileSync(${JSON.stringify(join(project, "settle-result.txt"))}, body);
        update('Self-settle tool returned: {"settlesWhenTurnEnds":true}\\nWork complete.');
        return {stopReason: "end_turn"};
        const turns = loadTurns(session.model);`);
  // Preserve the stock replay's transcript URLs when loading from this generated fixture.
  await writeFile(agentPath, custom.replaceAll('new URL(scenario.file, import.meta.url)', `new URL(scenario.file, ${JSON.stringify(new URL(`file://${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`).href)})`));
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.settleReplay = {driver: "acpRegistry", displayName: "Settle replay", enabled: true, config: {source: "local", commandPath: process.execPath, commandArgs: [agentPath]}};
  await writeFile(settingsPath, JSON.stringify(settings));
  await new Promise(r => setTimeout(r, 2000));
  const { cli } = makeState(T3_HOME);
  const started = JSON.parse((await runPromise(cli(["thread", "start", project, "Run foreground work, then finish.", "--title", "Pending self-settle", "--provider", "settleReplay", "--model", "showcase", "--json"]))).stdout);
  await t3.open(started);
  await screen.getByText("Work is running.", {exact: false}).waitFor({state: "visible"});
  await runPromise(cli(["thread", "send", started.threadId, "When you are done, settle this thread with t3_thread_organize (action settle) as your very last tool call."]));
  await screen.getByRole("button", "Send now").tap();
  await app.screenshot("steered-message");
  await writeFile(gate, "finish");
  await screen.getByText("Work complete.", {exact: false}).waitFor({state: "visible"});
  await screen.getByRole("button", "Stop generation").waitFor({state: "hidden"});
  // Give the asynchronous post-turn settle worker time to publish its event before capturing.
  await new Promise(r => setTimeout(r, 2000));
  await app.screenshot("turn-ended");
  await expect(screen.getByRole("button", "Un-settle")).toBeVisible();
});
