/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

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

test("Worktree choices exclude unborn repositories, count eligible defaults, and refresh after a first commit", WEB, async ({t3, app, browser, screen}) => {
  mkdirSync(join(T3_HOME, "workspaces"), {recursive:true});
  const fixture = async (title: string, names: string[]) => {
    const parent = mkdtempSync("/tmp/factory-pr-47437-evidence-1/run-");
    const folder = join(parent, title);
    mkdirSync(folder);
    writeFileSync(join(folder, "t3.json"), '{"defaultThreadEnvMode":"worktree"}');
    for (const name of [...names, "scratch"]) {
      const repo = join(folder, name);
      mkdirSync(repo);
      git(repo, "init", "--quiet", "--initial-branch=main");
      writeFileSync(join(repo, "README.md"), `${name}\n`);
      if (name !== "scratch") {
        git(repo, "add", ".");
        git(repo, ...author, "commit", "--quiet", "-m", "Initial commit");
      }
    }
    const added = await runPromise(makeState(T3_HOME).cli(["project", "add", folder]));
    const id = /Added project (\S+) /.exec(added.stdout)?.[1];
    if (!id) throw new Error("Fixture project was not added");
    t3.trackProject(id);
    return {folder, id};
  };
  const services = await fixture("services", ["api"]);
  const nine = await fixture("nine", Array.from({length:8}, (_,i)=>`svc${i+1}`));
  await t3.open();
  await browser.locator("[data-draft-project-trigger]").click();
  await screen.getByRole("option", "services", {exact:true}).click();
  const openMenu = async () => {
    await screen.getByRole("button", /^Repositories in the new worktree/).click();
  };
  await openMenu();
  await screen.getByRole("menuitemcheckbox", "api").waitFor();
  await app.screenshot("services-before-first-commit");
  const initial = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="menuitemcheckbox"]')).map(el => el.textContent?.trim()));
  await browser.keyboard.press("Escape");
  const scratch = join(services.folder, "scratch");
  git(scratch, "add", ".");
  git(scratch, ...author, "commit", "--quiet", "-m", "First scratch commit");
  await openMenu();
  await screen.getByRole("menuitemcheckbox", "scratch").waitFor();
  await app.screenshot("services-after-first-commit-and-reopen");
  await browser.keyboard.press("Escape");
  await browser.locator("[data-draft-project-trigger]").click();
  await screen.getByRole("option", "nine", {exact:true}).click();
  await openMenu();
  await screen.getByRole("menuitemcheckbox", "svc1").waitFor();
  await app.screenshot("eight-eligible-plus-unborn");
  const selected = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="menuitemcheckbox"][aria-checked="true"]')).map(el => el.textContent?.trim()));
  await expect(initial).toEqual(["api"]);
  await expect(selected).toEqual(["svc1", "svc2", "svc3", "svc4", "svc5", "svc6", "svc7", "svc8"]);
});
