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

test("Worktree launches reject a plain project before creating threads", WEB, async ({ t3, app, screen }) => {
  const project = await mkdtemp("/tmp/worktree-launch-proof/collection-");
  const { cli } = makeState(T3_HOME);
  for (const name of ["first-repository", "second-repository"]) {
    await mkdir(`${project}/${name}`);
    execFileSync("git", ["init", "--quiet"], { cwd: `${project}/${name}` });
  }
  await runPromise(cli(["project", "add", project, "--title", "Repository collection"]));
  await t3.thread({ project, title: "Launch context", messages: ["Ready"] });
  const outcomes = [];
  for (const ref of ["origin/master", ":/initial"]) {
    const result = await runPromise(cli(["thread", "start", project, "Start work", "--title", `Worktree ${ref}`, "--worktree", ref, "--provider", "devReplay", "--model", "multi-turn", "--json"], [0, 1]));
    outcomes.push({ ref, ...result });
    console.log(JSON.stringify({ ref, ...result }));
  }
  const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  await writeFile(`/tmp/worktree-launch-proof/${sha}-launch-results.json`, JSON.stringify(outcomes).replaceAll(project, "<synthetic project folder>"));
  await t3.open();
  await screen.getByText("Launch context", { exact: true }).first().tap();
  if (outcomes[1].exitCode === 0) await screen.getByText("Worktree :/initial", { exact: true }).first().tap();
  await app.screenshot("worktree-launch-result");
  for (const result of outcomes) {
    expect(result.exitCode).toBe(1);
    expect(result.stderr).toContain("not a Git repository");
  }
});
