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

// Synthetic native transcripts only; no provider turn is started.
test("Repeated imports reach the oldest linked-worktree conversation", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1440, height: 1000 });
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
  await t3.project("Scenario workspace");
  const project = `/tmp/factory-pr-36608-evidence-2/run-${Date.now()}/Worktree-history`;
  await mkdir(project, { recursive: true });
  execFileSync("git", ["init", "--quiet", "--initial-branch=main", project]);
  await writeFile(`${project}/README.md`, "Synthetic worktree import proof\n");
  execFileSync("git", ["-C", project, "add", "."]);
  execFileSync("git", ["-C", project, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial"]);
  const linked = `${project}-linked`;
  execFileSync("git", ["-C", project, "worktree", "add", "-b", "linked-history", linked]);
  const sessions = `${process.env.CODEX_HOME}/sessions/2026/11/14`;
  await mkdir(sessions, { recursive: true });
  for (let n = 1; n <= 101; n++) {
    const timestamp = new Date(Date.now() - n * 60_000).toISOString();
    const id = `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
    const title = n === 101 ? "Oldest conversation 101" : `Worktree conversation ${String(n).padStart(3, "0")}`;
    const records = [
      { timestamp, type: "session_meta", payload: { id, cwd: linked, source: "cli" } },
      { timestamp, type: "event_msg", payload: { type: "user_message", message: title } },
      { timestamp, type: "response_item", payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: `Synthetic linked-worktree history ${n}.` }] } },
    ];
    const file = `${sessions}/rollout-${id}.jsonl`;
    await writeFile(file, records.map(r => JSON.stringify(r)).join("\n") + "\n");
    await utimes(file, new Date(timestamp), new Date(timestamp));
  }
  const { cli } = makeState(T3_HOME);
  const threads = async () => JSON.parse((await runPromise(cli(["thread", "list", "--project", project, "--json"]))).stdout);
  const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
  const capture = async (label: string) => {
    // Keep only captures after the layout and overlays have settled.
    await pause(1500);
    let prior = await app.screenshot(`${label}-stability`);
    for (let n = 0; n < 8; n++) {
      await pause(500);
      const next = await app.screenshot(label);
      if ((await readFile(prior)).equals(await readFile(next))) return;
      prior = next;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const welcome = async () => {
    await t3.open("/settings/about");
    await screen.getByRole("link", "Open", { exact: true }).tap();
    await screen.getByRole("button", "Review all 1", { exact: true }).tap();
    const selectAll = screen.getByRole("button", "Select all", { exact: true });
    if (await selectAll.isEnabled()) await selectAll.tap();
  };
  const importNow = async () => {
    await screen.getByRole("button", /^Import (1 project and start|threads and start)$/).tap();
    await browser.waitForURL(/\/(?!welcome|settings)[^/]+\/[^/]+/, { timeout: 120_000 });
    await pause(7000); // Let the result toast leave before comparing the same layout.
  };
  await welcome();
  await importNow();
  const first = await threads();
  const newest = first.find((t: any) => t.title === "Worktree conversation 001");
  if (!newest) throw new Error("First import did not create the newest conversation");
  await t3.open({ threadId: newest.threadId });
  await screen.getByText("Synthetic linked-worktree history 1.", { exact: true }).waitFor({ timeout: 30_000 });
  await screen.getByRole("button", /^Dismiss Codex provider/).tap();
  await capture("001-first-import-readable-history");
  await welcome();
  await importNow();
  await t3.open({ threadId: newest.threadId });
  await screen.getByText("Synthetic linked-worktree history 1.", { exact: true }).waitFor();
  const secondDismiss = screen.getByRole("button", /^Dismiss Codex provider/);
  if (await secondDismiss.count()) await secondDismiss.tap();
  await capture("002-second-import-result");
  await screen.getByRole("combobox", "Search threads").fill("101");
  await pause(2000);
  const dismiss = screen.getByRole("button", /^Dismiss Codex provider/);
  if (await dismiss.count()) await dismiss.tap();
  await screen.getByRole("combobox", "Search threads").press("Home");
  await screen.getByRole("combobox", "Search threads").press("Tab");
  await capture("003-second-import-oldest-search");
  // The bug is precisely whether a second import reaches the 101st conversation.
  await expect(screen.getByRole("option", /Oldest conversation 101/)).toBeVisible({ timeout: 10_000 });
  const oldest = (await threads()).find((t: any) => t.title === "Oldest conversation 101");
  await screen.getByRole("combobox", "Search threads").fill("");
  await t3.open({ threadId: oldest.threadId });
  await expect(screen.getByText("Synthetic linked-worktree history 101.", { exact: true })).toBeVisible({ timeout: 30_000 });
  const lastDismiss = screen.getByRole("button", /^Dismiss Codex provider/);
  if (await lastDismiss.count()) await lastDismiss.tap();
  await capture("004-oldest-readable-history");
  await expect(screen.getByText("Synthetic linked-worktree history 101.", { exact: true })).toBeVisible();
});
