import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Adding a repository refuses the checkout hook's link to an empty external directory", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("app", {".gitignore": "vendor/\n"});
  const lib = path.join(project, "vendor/lib");
  const empty = path.join(path.dirname(project), "fx/empty");
  const hooks = path.join(project, ".git/proof-hooks");
  await fs.mkdir(lib, {recursive:true});
  await fs.mkdir(empty, {recursive:true});
  await fs.mkdir(hooks, {recursive:true});
  const git = (cwd:string, args:string[]) => runPromise(run("git", args, {cwd}));
  await git(lib, ["init", "--quiet", "--initial-branch=main"]);
  await fs.writeFile(path.join(lib, "README.md"), "Independent library\n");
  await git(lib, ["add", "."]);
  await git(lib, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial library"]);
  await fs.writeFile(path.join(hooks, "post-checkout"), `#!/bin/sh\nmkdir -p vendor\nln -s '${empty}' vendor/lib\n`, {mode:0o755});
  await git(project, ["config", "core.hooksPath", hooks]);
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "hello", "--title", "Hook-linked repository", "--worktree", "main", "--branch", "t3/hello", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  // Redact the machine-local prefix in the error display only; the guard and assertions are real.
  await browser.addInitScript(() => {
    new MutationObserver(() => {
      if (!document.body) return;
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.nodeValue?.includes("already holds files") && node.nodeValue.includes("/home/")) {
          node.nodeValue = node.nodeValue.replace(/\/home\/[^ ]+\/vendor\/lib/g, "<thread>/vendor/lib");
        }
      }
    }).observe(document, {subtree:true, childList:true, characterData:true});
  });
  await t3.open(JSON.parse(started.stdout));
  await screen.getByRole("button", "Other repositories...", {exact:true}).tap({timeout:60000});
  await screen.getByRole("menuitem", /lib/).tap();
  await screen.getByRole("button", "Other repositories...", {exact:true}).waitFor();
  try {
    await expect(screen.getByText(/already holds files, so no worktree can go there/)).toBeVisible();
    expect(await fs.readdir(empty)).toEqual([]);
    await expect(screen.getByRole("group", "Repository lib", {exact:true})).toHaveCount(0);
  } finally {
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
    await app.screenshot("after-adding-hook-linked-repository");
  }
});
