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

test("A filename citation opens one file listed by overlapping projects", WEB, async ({ t3, app, screen }) => {
  const repository = await t3.project("handoff-repository", {
    "docs/quarterly-handoff.txt": "QUARTERLY HANDOFF: The shared release is ready for review.\n",
  });
  await runPromise(makeState(T3_HOME).cli(["project", "add", `${repository}/docs`, "--title", "handoff-docs"]));
  const third = await t3.project("planning-workspace");
  const recording = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = await readFile(recording, "utf8");
  const runtime = `${T3_HOME}/userdata/server-runtime.json`;
  const previous = await readFile(runtime, "utf8");
  await writeFile(recording, original.replaceAll("first fixture turn complete", "See [quarterly-handoff.txt](quarterly-handoff.txt) for the release handoff."));
  const deadline = Date.now() + 60000;
  while (true) {
    try {
      const current = await readFile(runtime, "utf8");
      if (current !== previous && (await fetch(`${JSON.parse(current).origin}/.well-known/t3/environment`)).ok) break;
    } catch {}
    if (Date.now() > deadline) throw new Error("Replay fixture server restart did not finish");
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  const thread = await t3.thread({ project: third, title: "Review the quarterly handoff", messages: ["Cite the quarterly handoff file by filename alone."], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByRole("link", "quarterly-handoff.txt").tap();
  await app.screenshot("quarterly-handoff-opened");
  await expect(screen.getByText("QUARTERLY HANDOFF: The shared release is ready for review.", { exact: false })).toBeVisible();
  await app.screenshot("quarterly-handoff-result");
});
