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

test("Grouped repository opens the root added after its subfolders", {...WEB, video:"off"}, async ({t3, app, screen, browser}) => {
  const parent = await mkdtemp("/tmp/factory-issue-36296-evidence-3/work-");
  const repo = `${parent}/workspace`;
  for (const folder of ["_archive/old-tool", "app-a", "app-b"]) {
    await mkdir(`${repo}/${folder}`, {recursive:true});
    await writeFile(`${repo}/${folder}/README.md`, "Synthetic project fixture\n");
  }
  execFileSync("git", ["init", "--quiet", "--initial-branch=main", repo]);
  execFileSync("git", ["-C", repo, "remote", "add", "origin", "https://github.com/owner/workspace.git"]);
  const {cli} = makeState(T3_HOME);
  for (const folder of ["_archive/old-tool", "app-a", "app-b", ""]) {
    await runPromise(cli(["project", "add", folder ? `${repo}/${folder}` : repo]));
  }
  const notes = `${parent}/notes`;
  await mkdir(notes);
  await writeFile(`${notes}/README.md`, "Navigation fixture\n");
  execFileSync("git", ["init", "--quiet", "--initial-branch=main", notes]);
  await runPromise(cli(["project", "add", notes]));
  const navigationThread = await t3.thread({project:notes,title:"Navigation fixture",messages:["Navigation fixture"],model:"showcase"});
  await t3.open(navigationThread);
  await screen.getByRole("button", "New thread", {exact:true}).waitFor();
  await app.startRecording();
  await screen.getByRole("button", "New thread", {exact:true}).tap();
  await app.screenshot("repository-picker");
  await screen.getByRole("option", /owner\/workspace/).tap();
  await app.screenshot("new-thread-folder");
  try {
    await expect(screen.getByRole("heading").getByRole("combobox")).toHaveText("workspace");
  } finally {
    await app.open("/settings/projects");
    await screen.getByRole("button", "Project scope: All projects").tap();
    await screen.getByRole("menuitemradio").filter({hasText:"owner/workspace"}).tap();
    await screen.getByRole("button", `Remove checkout ${repo}`, {exact:true}).scrollIntoView();
    await app.screenshot("web-settings-checkout-order");
  }
});
