/// <reference lib="dom" />
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// Evidence observes the real client's optional RPC and the real server's trace, without altering either.
test("Opening a settled thread after cleanup reads optional t3.json without an error", WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.addInitScript(() => {
      const requests = new Map<string, unknown>();
      const results: unknown[] = [];
      Object.assign(window, { optionalReadResults: results });
      const send = WebSocket.prototype.send;
      const watched = new WeakSet<WebSocket>();
      WebSocket.prototype.send = function(data) {
        if (typeof data === "string") for (const msg of [JSON.parse(data)].flat()) {
          if (msg?._tag === "Request" && msg.tag === "projects.readFile" && msg.payload?.allowMissing)
            requests.set(String(msg.id), msg.payload);
        }
        if (!watched.has(this)) {
          watched.add(this);
          this.addEventListener("message", event => {
            if (typeof event.data !== "string") return;
            for (const msg of [JSON.parse(event.data)].flat()) {
              if (msg?._tag === "Exit" && requests.has(String(msg.requestId)))
                results.push({ input: requests.get(String(msg.requestId)), exit: msg.exit });
            }
          });
        }
        return send.call(this, data);
      };
    });
    const project = await t3.project("cleanup-demo", { "t3.json": '{}\n' });
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project, "go", "--title", "Cleanup reproduction", "--worktree", "main", "--branch", "t3/cleanup-repro", "--provider", "devReplay", "--model", "todo-list", "--wait", "--json"]));
    const thread = JSON.parse(started.stdout);
    const shown = JSON.parse((await runPromise(cli(["thread", "show", thread.threadId, "--json"]))).stdout);
    const worktree = shown.thread.worktreePath;
    await t3.open(thread);
    // Hover makes the sidebar action available, matching the normal sidebar interaction.
    await screen.getByRole("button", "Cleanup reproduction, cleanup-demo").hover();
    await screen.getByRole("button", "Settle thread").tap();
    await t3.open("/settings/worktrees");
    await screen.getByRole("button", "Advanced").last().tap();
    await screen.getByRole("switch", "Delete unchanged worktrees").tap();
    // Cleanup deliberately protects threads settled less than sixty seconds ago.
    await setTimeout(65_000);
    await t3.open("/settings/maintenance");
    await screen.getByRole("button", "Delete now").tap();
    await screen.getByText("1 removed", { exact: false }).first().waitFor({ state: "visible" });
    await app.screenshot("cleanup-removed-worktree");
    const tracePath = `${T3_HOME}/userdata/logs/server.trace.ndjson`;
    const before = await readFile(tracePath, "utf8");
    await t3.open(thread);
    await screen.getByRole("textbox").waitFor({ state: "visible" });
    // Wait for the observed RPC to settle on either revision; its outcome is the assertion below.
    let result: any = null;
    for (let i = 0; i < 100; i++) {
      result = await browser.evaluate(() => (window as any).optionalReadResults.at(-1) ?? null);
      if (result) break;
      await setTimeout(100);
    }
    await setTimeout(1000); // The trace writer batches records before flushing them.
    const after = (await readFile(tracePath, "utf8")).slice(before.length);
    const failures = after.split("\n").filter(line => line.includes("realpath-workspace-root"));
    const sanitize = (text: string) => text.split(T3_HOME).join("<scenario-home>").split(worktree).join("<removed-worktree>").replaceAll(/\/home\/[^/\s"\\]+/g, "<home>");
    const transcript = sanitize(JSON.stringify({ optionalRead: result, matchingFailureSpans: failures.map(line => JSON.parse(line)) }, null, 2));
    const out = `/tmp/factory-pr-37747-evidence-1/${Date.now()}`;
    await mkdir(out, { recursive: true });
    await writeFile(`${out}/server-observation.json`, transcript);
    await browser.evaluate(({ count, result }) => {
      const panel = document.createElement("pre");
      panel.id = "evidence-observer";
      panel.style.cssText = "position:fixed;bottom:16px;left:300px;right:16px;z-index:99999;padding:20px;background:#111827;color:#f3f4f6;border:2px solid #64748b;border-radius:8px;font:15px/1.6 monospace;white-space:pre-wrap";
      panel.textContent = `EVIDENCE OBSERVER — real WebSocket response + server trace\nWorktree removed by Maintenance → Delete now\nReopened settled thread; optional t3.json (allowMissing: true)\nRPC outcome: ${result?.exit?._tag ?? "not observed"}\nexists: ${result?.exit?.value?.exists ?? "no result"}\nrealpath-workspace-root failure spans: ${count}\n${count ? "ENOENT → WorkspaceFileSystemOperationError → ProjectReadFileError" : "No filesystem error logged for this read"}`;
      document.body.append(panel);
      return null;
    }, { count: failures.length, result });
    await app.screenshot("optional-read-server-observation");
    await expect(result?.exit?._tag).toBe("Success");
    await expect(result?.exit?.value?.exists).toBe(false);
    await expect(failures.length).toBe(0);
  });
