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

const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const init = (directory: string) => {
  mkdirSync(directory, { recursive: true });
  git(directory, "init", "--quiet", "--initial-branch=main");
  writeFileSync(join(directory, "README.md"), "Synthetic repository\n");
  git(directory, "add", ".");
  git(directory, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial commit");
};

test("A superseded submodule path leaves the independent repository discoverable", WEB, async ({ t3, app, screen, browser }) => {
  const parent = await t3.project("parent");
  const control = await t3.project("control");
  for (const [root, superseded] of [[parent, true], [control, false]] as const) {
    const source = join(dirname(root), "shared-src");
    init(source);
    git(root, "-c", "protocol.file.allow=always", "submodule", "add", "--name", "shared", "../shared-src", "real");
    init(join(root, "unrelated"));
    writeFileSync(join(root, ".gitmodules"), `[submodule "shared"]\n${superseded ? "\tpath = unrelated\n" : ""}\tpath = real\n\turl = ../shared-src\n`);
    if (git(root, "config", "--file", ".gitmodules", "--get", "submodule.shared.path") !== "real") throw new Error("Fixture does not resolve to real");
    if (!git(root, "submodule", "status").includes("real")) throw new Error("Real submodule not initialized");
  }
  await t3.thread({ project: parent, title: "Repository discovery", messages: ["Hello"] });
  await t3.open("/settings/projects");
  await screen.getByRole("button", "Project scope: All projects").tap();
  await screen.getByRole("menuitemradio").filter({ hasText: "control" }).tap();
  // Redact host paths only; repository names and discovery results remain unchanged.
  const redactPaths = () => browser.evaluate(() => {
    for (const element of document.querySelectorAll("*")) {
      if (element.children.length === 0 && element.textContent?.startsWith("/home/")) {
        element.textContent = "[synthetic workspace]/" + element.textContent.split("/").at(-1);
      }
    }
    return null;
  });
  const repositories = browser.locator("#project-repositories");
  await repositories.scrollIntoView();
  await expect(repositories.getByRole("heading", "unrelated Git repository", { exact: true })).toBeVisible();
  await redactPaths();
  await app.screenshot("control-repositories");
  await screen.getByRole("button", "Project scope: control").tap();
  await screen.getByRole("menuitemradio").filter({ hasText: "parent" }).tap();
  await repositories.scrollIntoView();
  try {
    await expect(repositories.getByRole("heading", "unrelated Git repository", { exact: true })).toBeVisible();
    await expect(repositories.getByRole("heading", "real Git repository", { exact: true })).toBeHidden();
  } finally {
    await redactPaths();
    await app.screenshot("parent-repositories");
  }
});
