import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" });
const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];

test("Checkpoint capture excludes literal colon-prefixed nested repositories", WEB, async ({ t3, app, screen, browser }) => {
  const cases: { name: string; nested: string; project: string; threadId?: string }[] = [];
  for (const [name, nested, ignore] of [["plain", "plain", ""], ["foo", ":(foo)", ""], ["shadow", ":shadow", "shadow\n"]]) {
    const project = await t3.project(`parent-${name}`, { "app.txt": "hello\n", ...(ignore ? { ".gitignore": ignore } : {}) });
    const child = `${project}/${nested}`;
    mkdirSync(child);
    writeFileSync(`${child}/nested.txt`, "Nested repository must stay separate\n");
    git(child, "init", "--quiet", "--initial-branch=main");
    git(child, "add", "--all");
    git(child, ...author, "commit", "--quiet", "-m", "Nested initial commit");
    cases.push({ name, nested, project });
  }
  const cli = makeState(T3_HOME).cli;
  for (const item of cases) {
    const started = await runPromise(cli(["thread", "start", item.project, "Append a new line containing exactly world to app.txt", "--title", `Checkpoint ${item.nested}`, "--provider", "devReplay", "--model", "multi-turn", "--json"]));
    item.threadId = JSON.parse(started.stdout).threadId;
    await t3.open({ threadId: item.threadId! });
    // Replay emits real turn events; the driver supplies the deterministic workspace edit.
    writeFileSync(`${item.project}/app.txt`, "hello\nworld\n");
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  }
  const inspect = () => cases.map(item => {
    const refs = git(item.project, "for-each-ref", "--format=%(refname)", "refs/t3/").trim().split("\n").filter(Boolean);
    return { name: item.name, nested: item.nested, checkpoints: refs.length, trees: refs.map(ref => git(item.project, "ls-tree", "-r", ref)) };
  });
  // Wait for the successful control's final capture, independently of the broken cases.
  await expect.poll(() => inspect()[0].checkpoints).toBe(2);
  const report = inspect();
  const current = cases[2];
  writeFileSync(`${current.project}/checkpoint-report.txt`, report.map(item => `parent-${item.name} / ${item.nested} | checkpoint refs: ${item.checkpoints}\n${item.trees.map((tree, i) => `  ordinal ${i}: ${tree.trim().split("\n").map(line => line.split("\t")[1]).join(", ")}\n`).join("")}`).join("\n"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.waitFor();
  await input.focus();
  await browser.keyboard.type("unset PROMPT_COMMAND; PS1='$ '; clear; cat checkpoint-report.txt; touch report.done\n");
  await expect.poll(() => existsSync(`${current.project}/report.done`)).toBe(true);
  await app.screenshot("checkpoint-trees");
  await expect.poll(() => inspect().map(item => ({ name: item.name, checkpoints: item.checkpoints, containsNested: item.trees.some(tree => tree.includes("160000")) })) ).toEqual(cases.map(item => ({ name: item.name, checkpoints: 2, containsNested: false })));
});
