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

// The replay provider runs the same shell writes as the reported agent; all app code stays real.
test("An atomically replaced outside HTML preview renews its signed URL", WEB, async ({ t3, app, screen, browser }) => {
  const scratch = process.env.T3_PROOF_SCRATCH!;
  const outside = await mkdtemp(join(scratch, "report-"));
  const report = join(outside, "report.html");
  const agent = join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts");
  const transcript = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const originalAgent = await readFile(agent, "utf8");
  const originalTranscript = await readFile(transcript, "utf8");
  const html = (version: string, color: string) => `<!doctype html><html><body style="background:${color};font-family:system-ui;padding:32px"><h1>Report ${version}</h1><p>Outside-workspace HTML preview</p></body></html>`;
  const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
  const commands = [
    `printf %s ${quote(html("v1 ORIGINAL", "#ffe780"))} > ${quote(report)}`,
    `printf %s ${quote(html("v2 EDITED", "#b4efba"))} > ${quote(report + ".tmp")} && mv ${quote(report + ".tmp")} ${quote(report)}`,
  ];
  const entries = ["Report created. [report.html](" + report + ")", "Atomic replacement complete."].flatMap((text, index) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "tool_call", toolCallId: `shell-${index}`, title: index === 0 ? "Create original report with bash" : "Atomically replace report with bash", kind: "execute", status: "completed", content: [] } } } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]);
  try {
    await writeFile(transcript, entries.map(entry => JSON.stringify(entry)).join("\n"));
    await writeFile(agent, originalAgent.replace('#!/usr/bin/env node', '#!/usr/bin/env node\nimport { execFileSync as proofShell } from "node:child_process";').replace('const turns = loadTurns(session.model);', `proofShell("bash", ["-c", ${JSON.stringify(commands)}[session.promptCount % 2]], { cwd: session.cwd });\n        const turns = loadTurns(session.model);`));
    // Source-backed replay fixtures trigger the dev watcher; let setup restart before seeding.
    await new Promise(resolve => setTimeout(resolve, 5000));
    const project = await t3.project("HTML preview demo");
    const thread = await t3.thread({ project, title: "Outside report", messages: ["Create the original HTML report outside the workspace."], model: "multi-turn" });
    await t3.open(thread);
    await screen.getByRole("link", "report.html").tap();
    const frame = browser.frameLocator("iframe");
    await frame.getByRole("heading", "Report v1 ORIGINAL").waitFor({ state: "visible" });
    await app.screenshot("original-report");
    const inode = (await stat(report)).ino;
    const { cli } = makeState(T3_HOME);
    await runPromise(cli(["thread", "send", thread.threadId, "Atomically replace the report with the edited version.", "--wait", "--json"]));
    if ((await stat(report)).ino === inode) throw new Error("Fixture did not atomically replace the file");
    try {
      await expect(frame.getByRole("heading", "Report v2 EDITED")).toBeVisible({ timeout: 15_000 });
    } finally {
      // Keep the completed frame visible long enough for the recording to include it.
      await new Promise(resolve => setTimeout(resolve, 1000));
      await app.screenshot("after-atomic-replacement");
      await new Promise(resolve => setTimeout(resolve, 1500));
    }
  } finally {
    await writeFile(agent, originalAgent);
    await writeFile(transcript, originalTranscript);
  }
});
