import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, chmodSync } from "node:fs";
import { test, WEB } from "./t3.ts";

test("A checkout hook may link an auto-discovered ignored vendor repository", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("app", { ".gitignore": "vendor/lib/\n", "README.md": "Vendor hook reproduction\n" });
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd });
  mkdirSync(`${project}/vendor/lib`, { recursive: true });
  git(`${project}/vendor/lib`, "init", "--quiet", "--initial-branch=main");
  writeFileSync(`${project}/vendor/lib/README.md`, "Independent vendor repository\n");
  git(`${project}/vendor/lib`, "add", ".");
  git(`${project}/vendor/lib`, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Vendor initial commit");
  mkdirSync(`${project}/.git/scenario-hooks`);
  const hook = `${project}/.git/scenario-hooks/post-checkout`;
  writeFileSync(hook, `#!/bin/sh\nif [ "$(git rev-parse --show-toplevel)" != '${project}' ]; then\n mkdir -p vendor\n ln -s '${project}/vendor/lib' vendor/lib\nfi\n`);
  chmodSync(hook, 0o755);
  git(project, "config", "core.hooksPath", `${project}/.git/scenario-hooks`);
  await t3.open();
  await screen.getByRole("button", "Run context: Scenario, Current checkout").tap();
  await screen.getByRole("menuitemradio", "New worktree").tap();
  await screen.getByRole("button", "Showcase", { exact: false }).first().tap();
  await browser.keyboard.type("Multi turn");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  await screen.getByRole("textbox").fill("hello");
  await screen.getByRole("textbox").press("Enter");
  try {
    await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({ timeout: 90000 });
    await expect(screen.getByRole("button", "Stop generation")).toBeHidden({ timeout: 30000 });
  } finally {
    await app.screenshot("worktree-result");
  }
});
