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

test("Explicit existing branches are rejected before creating a thread", WEB, async ({ t3, app, screen }) => {
  const seed = await t3.project("fixture-seed");
  const directory = `/tmp/factory-pr-31279-evidence-3/run-${Date.now()}`;
  mkdirSync(directory, { recursive: true });
  const project = `${directory}/branch-launch-demo`;
  await runPromise(run("git", ["clone", "--quiet", seed, project]));
  const { cli } = makeState(T3_HOME);
  await runPromise(cli(["project", "add", project, "--title", "branch-launch-demo"]));
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("worktree", "add", "-b", "feature/taken", `${project}-occupied`);
  await git("branch", "feature/idle");
  const launch = (branch: string, wait = false) => runPromise(cli([
    "thread", "start", project, "reply ok", "--title", `Launch ${branch}`,
    "--json", "--worktree", "main", "--branch", branch,
    "--provider", "devReplay", "--model", "multi-turn", ...(wait ? ["--wait"] : []),
  ], [0, 1, 2]));
  const attempts = [];
  for (const branch of ["feature/taken", "feature/idle", "main"]) {
    attempts.push({ branch, ...await launch(branch) });
  }
  const control = await launch("feature/unused-control", true);
  const listed = await runPromise(cli(["thread", "list", "--project", project, "--json"]));
  const threads = JSON.parse(listed.stdout);
  const first = attempts[0];
  const target = first.exitCode === 0 ? JSON.parse(first.stdout) : threads.find((t: { title: string }) => t.title === "Launch feature/unused-control");
  await t3.open(target);
  if (first.exitCode === 0) {
    await screen.getByText("Workspace preparation failed", { exact: true }).first().waitFor();
  }
  await screen.getByRole("textbox", `Message Launch ${first.exitCode === 0 ? "feature/taken" : "feature/unused-control"}`).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("branch-launch-result");
  const output = { attempts, control, threads };
  const safe = JSON.stringify(output, null, 2).replaceAll(project, "<demo-repository>").replaceAll(T3_HOME, "<isolated-home>").replaceAll(APP_DIR, "<app-checkout>");
  writeFileSync(`${directory}/cli-transcript.json`, safe);
  console.log(safe);
  for (const attempt of attempts) {
    expect(attempt.exitCode).toBe(1);
    expect(attempt.stderr).toContain(attempt.branch);
  }
  expect(threads.length).toBe(1);
  expect(control.exitCode).toBe(0);
});
