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

test("Committed patterns select new worktree files and missing patterns prevent creation", WEB, async ({ t3, app, browser, screen }) => {
  const files = {
    "src/app.txt": "Application source\n",
    "assets/excluded.txt": "Excluded asset\n",
    "sparse-patterns.txt": "/*\n!/assets/\n",
    "t3.json": JSON.stringify({ worktreeSparsePatternsPath: "sparse-patterns.txt" }),
  };
  const project = await t3.project("Sparse checkout", files);
  const missing = await t3.project("Missing patterns", { ...files, "t3.json": JSON.stringify({ worktreeSparsePatternsPath: "nonexistent-patterns.txt" }) });
  const git = async (cwd: string, ...args: string[]) => (await runPromise(run("git", args, { cwd }))).stdout;
  const start = async (cwd: string, branch: string) => runPromise(run(process.execPath, [
    "apps/server/src/bin.ts", "thread", "start", cwd, "Verify configured worktree checkout", "--title", "Sparse checkout proof", "--worktree", "main", "--branch", branch,
    "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json", "--base-dir", T3_HOME,
  ], { cwd: APP_DIR, env: { PATH: process.env.PATH, HOME: process.env.HOME }, allowExit: [0, 1, 2] }));
  const started = await start(project, "proof/sparse");
  const launched = JSON.parse(started.stdout);
  const list = await git(project, "worktree", "list", "--porcelain");
  const worktree = list.split("\n\n").find((entry) => entry.includes("branch refs/heads/proof/sparse"))!.split("\n")[0]!.slice(9);
  const exists = async (file: string) => access(file).then(() => true, () => false);
  const source = await exists(`${worktree}/src/app.txt`);
  const asset = await exists(`${worktree}/assets/excluded.txt`);
  const bad = await start(missing, "proof/missing");
  const badResult = JSON.parse(bad.stdout);
  const missingError = String(badResult.error ?? "").match(/t3\.json names the sparse-checkout pattern file[^\n]*/)?.[0] ?? "No sparse-pattern configuration error";
  const badBranch = (await git(missing, "branch", "--list", "proof/missing")).trim() !== "";
  const badWorktree = (await git(missing, "worktree", "list", "--porcelain")).includes("branch refs/heads/proof/missing");
  const report = [
    "REAL SERVER WORKTREE CHECKOUT", "",
    't3.json: {"worktreeSparsePatternsPath":"sparse-patterns.txt"}',
    "Committed patterns: /*  then  !/assets/", "",
    `src/app.txt: ${source ? "PRESENT" : "ABSENT"}`,
    `assets/excluded.txt: ${asset ? "PRESENT (full checkout)" : "ABSENT (excluded by patterns)"}`, "",
    "MISSING PATTERN FILE: nonexistent-patterns.txt",
    missingError,
    `Thread startup: ${bad.exitCode === 0 ? "COMPLETED (configuration ignored)" : "FAILED before replay completion"}`,
    `New branch: ${badBranch ? "CREATED" : "NOT CREATED"}`,
    `New worktree: ${badWorktree ? "CREATED" : "NOT CREATED"}`, "",
    "Inspection complete.",
  ].join("\n");
  await writeFile(`${worktree}/checkout-proof.txt`, report);
  await t3.open({ threadId: launched.threadId });
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return readFile(`${worktree}/shell-ready`, "utf8").catch(() => "");
  }, { timeout: 30_000 }).toBe("ready\n");
  await terminal.focus();
  await browser.keyboard.type("clear; cat checkout-proof.txt; touch proof-displayed");
  await browser.keyboard.press("Enter");
  await expect.poll(() => exists(`${worktree}/proof-displayed`)).toBe(true);
  await app.screenshot("worktree-checkout");
  await expect({ sourceRetained: source, excludedAssetAbsent: !asset, missingBranchAbsent: !badBranch, missingWorktreeAbsent: !badWorktree, missingStartupFailed: bad.exitCode !== 0, missingFileError: missingError.includes("which is not a file in main") }).toEqual({ sourceRetained: true, excludedAssetAbsent: true, missingBranchAbsent: true, missingWorktreeAbsent: true, missingStartupFailed: true, missingFileError: true });
});
