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

test("Welcome discovers a main checkout from three worktree-only conversations", WEB, async ({ t3, app, screen, browser }) => {
  const root = process.env.DISCOVERY_FIXTURE_ROOT!;
  const claude = join(T3_HOME, "claude");
  const run = root;

  mkdirSync(run, { recursive: true });
  for (const [name, worktreeOnly] of [["control", false], ["worktree-only", true]] as const) {
    const main = join(run, name);
    if (!existsSync(main)) {
    mkdirSync(main);
    const git = (...args: string[]) => execFileSync("git", ["-C", main, ...args]);
    git("init", "--quiet", "--initial-branch=main");
    writeFileSync(join(main, "README.md"), "Synthetic discovery fixture\n");
    git("add", ".");
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit");
    git("remote", "add", "origin", `https://github.com/demo/${worktreeOnly ? "wt" : "main"}.git`);
    const linked = join(run, `${name}-linked`);
    git("worktree", "add", "--quiet", "-b", "feature", linked);
    }
    const linked = join(run, `${name}-linked`);
    execFileSync("git", ["-C", main, "remote", "set-url", "origin", `https://github.com/demo/${worktreeOnly ? "wt" : "main"}.git`]);
    const cwd = worktreeOnly ? linked : main;
    const dir = join(claude, "projects", cwd.replaceAll("/", "-"));
    mkdirSync(dir, { recursive: true });
    for (let i = 1; i <= 3; i++) {
      const sessionId = `${name}-${i}`;
      writeFileSync(join(dir, `${sessionId}.jsonl`), [
        { type: "user", uuid: `${sessionId}-u`, sessionId, cwd, timestamp: new Date().toISOString(), message: { role: "user", content: "Describe this repository" } },
        { type: "assistant", uuid: `${sessionId}-a`, parentUuid: `${sessionId}-u`, sessionId, cwd, timestamp: new Date().toISOString(), message: { role: "assistant", content: [{type:"text",text:"This is a synthetic repository."}] } },
      ].map(x => JSON.stringify(x)).join("\n") + "\n");
    }
  }
  await t3.open();
  await screen.getByRole("button", /^Review all/).tap();
  await app.screenshot("welcome-project-discovery");
  await expect(screen.getByText("demo/wt", { exact: true })).toBeVisible();
  await expect(browser.locator("label").filter({ hasText: "demo/wt" }).getByText("3", { exact: true })).toBeVisible();
});
