import { mkdir, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Successful thread creation has no failed projection-read span", WEB, async ({ t3, app, screen, browser }) => {
  await fetch("http://127.0.0.1:4318", { method: "DELETE" });
  await t3.project("trace-demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  await browser.addInitScript(() => {
    const redact = () => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        const clean = node.textContent?.replace(/\/(?:home|Users)\/[^\s)]+/g, "[private path]");
        if (clean !== node.textContent) node.textContent = clean ?? "";
      }
    };
    document.addEventListener("DOMContentLoaded", () => {
      new MutationObserver(redact).observe(document.body, { childList: true, subtree: true, characterData: true });
      redact();
    });
  });
  await t3.open();
  await screen.getByRole("textbox").fill("Give me a short tour");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("This turn is a replay.", { exact: false }).waitFor({ state: "visible", timeout: 60000 });
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
  await app.screenshot("created-thread");

  let spans: any[] = [];
  const deadline = Date.now() + 30000;
  do {
    spans = await (await fetch("http://127.0.0.1:4318")).json();
    if (spans.some((s) => s.name === "orchestrationV2.dispatch.threadCreate")) break;
    await new Promise((resolve) => setTimeout(resolve, 250));
  } while (Date.now() < deadline);
  if (!spans.some((s) => s.name === "orchestrationV2.dispatch.threadCreate")) throw new Error("Collector did not receive threadCreate span");
  const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  const output = `${process.env.PROOF_ARTIFACT_DIR}/run-${Date.now()}-${sha.slice(0, 10)}`;
  await mkdir(output, { recursive: true });
  await writeFile(`${output}/exported-spans.json`, JSON.stringify({ sha, spans }, null, 2));
  const summary = execFileSync(process.execPath, ["apps/server/src/bin.ts", "trace", "summary", "--base-dir", T3_HOME, "--limit", "200"], { cwd: APP_DIR, encoding: "utf8" });
  await writeFile(`${output}/trace-summary.txt`, summary);

  await t3.open("/settings/maintenance");
  await screen.getByRole("link", "View diagnostics").tap();
  await screen.getByRole("heading", "Latest Failures").scrollIntoView();
  await screen.getByRole("button", "Refresh trace diagnostics").tap();
  await screen.getByRole("heading", "Latest Failures").scrollIntoView();
  await browser.goto("http://127.0.0.1:4318/report");
  await app.screenshot("exported-thread-create-trace");
  const creates = spans.filter((s) => s.name === "orchestrationV2.dispatch.threadCreate");
  const failedReads = spans.filter((s) => s.name === "ProjectionStore.getThread" && Number(s.status?.code) === 2 && creates.some((c) => c.traceId === s.traceId));
  await expect(failedReads).toHaveLength(0);
});
