import { expect } from "e2e";
import { writeFile, readdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("Repository-relative worktree location prepares both project workspaces", WEB, async ({ t3, app, screen, browser }) => {
  const projects = [];
  for (const title of ["Orchard", "Meadow"]) {
    const repo = await t3.project(title, { ".gitignore": "CLAUDE.local.md\n", "README.md": `# ${title}\n` });
    await writeFile(join(dirname(repo), "CLAUDE.local.md"), "Instruction marker: ANCESTOR_MARKER\n");
    await writeFile(join(repo, "CLAUDE.local.md"), `Instruction marker: ${title.toUpperCase()}_LOCAL_MARKER\n`);
    projects.push({title, repo});
  }
  await t3.open();
  await screen.getByRole("button", "New thread in Orchard").tap();
  await app.open("/settings/worktrees");
  await screen.getByRole("textbox", "Worktree location").fill(".claude/worktrees");
  await browser.keyboard.press("Tab");
  await screen.getByRole("button", "Reset worktree location to default").waitFor();
  await app.screenshot("relative-location");
  await app.open("/");
  for (const {title, repo} of projects) {
    await screen.getByRole("button", `New thread in ${title}`).tap();
    await screen.getByRole("button", "Current checkout").tap();
    await screen.getByRole("menuitemradio", "New worktree").tap();
    await screen.getByRole("textbox").fill("Which instruction markers did you receive? Show the repository overview.");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText(/This turn is a replay\.|must be an absolute folder/).first().waitFor({timeout: 60000});
    await app.screenshot(`${title}-workspace-result`);
    await expect(screen.getByText("This turn is a replay.", { exact: false })).toBeVisible();
    const worktrees = await readdir(join(repo, ".claude/worktrees"));
    expect(worktrees.length).toBe(1);
    const status = execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], {cwd:repo, encoding:"utf8"});
    expect(status).toBe("");
    console.log(`${title}: checkout below .claude/worktrees; main checkout Git status clean`);
  }
});
