import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { chmod, writeFile, mkdir, mkdtemp } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Repeated slash SSH remotes share the alias-resolved control project", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = process.env.SSH_PROOF_FIXTURE!;
  // start-app already puts this private bin directory on its server's PATH.
  // This forwards every argument to real OpenSSH; no SSH output is simulated.
  const ssh = `${T3_HOME}/bin/ssh`;
  await writeFile(ssh, `#!/bin/sh\nexec /usr/bin/ssh -F '${fixture}/ssh_config' "$@"\n`);
  await chmod(ssh, 0o755);
  // Keep all projects until the runner stops recording, including after a failed expect.
  // Per-test t3 cleanup would otherwise remove groups in the tail of the base video.
  const seeded = makeState(T3_HOME);
  const state = seeded.state;
  const bare = `${fixture}/srv/git/repo.git`;
  const remotes = [
    `buildbox:${bare}`,
    `buildbox:${bare.replace("/srv/git/", "/srv//git/")}`,
    `buildbox:${bare}//`,
  ];
  const runRoot = await mkdtemp(`${fixture}/checkouts-`);
  const projects: string[] = [];
  for (const [index, name] of ["ssh-control", "ssh-interior", "ssh-trailing"].entries()) {
    const project = `${runRoot}/${name}`;
    await runPromise(run("git", ["clone", bare, project]));
    await runPromise(run("git", ["remote", "set-url", "origin", remotes[index]!], { cwd: project }));
    await runPromise(run("git", ["-c", `core.sshCommand=${ssh}`, "ls-remote", "origin"], { cwd: project }));
    await runPromise(seeded.cli(["project", "add", project, "--title", name]));
    projects.push(project);
  }
  const thread = await state.thread({ project: projects[0]!, title: "SSH remote identity", messages: ["Ready"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  await t3.open("/settings/projects");
  const scope = browser.locator('button[aria-label^="Project scope:"]');
  await scope.click();
  await app.screenshot("ssh-groups-initial");
  await runPromise(Effect.sleep("35 seconds"));
  await app.screenshot("ssh-groups-steady");
  // All projects is the extra menu item. Exactly one repository group must remain.
  await expect(browser.locator('[role="menuitemradio"]')).toHaveCount(2);

});
