import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";

test("Legacy GitLab alternate SSH projects open commits and merge requests on gitlab.com", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("gitlab-altssh", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }), ".git/config": '[remote "origin"]\n\turl = ssh://git@altssh.gitlab.com:443/group/project.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' });
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Second main commit"]);
  await git(["checkout", "-b", "feature"]);
  await writeFile(`${project}/README.md`, "A feature implemented through the alternate SSH remote.\n");
  await git(["add", "README.md"]);
  await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Feature commit"]);
  const sha = (await git(["rev-parse", "HEAD"])).stdout.trim();
  const thread = await t3.thread({ project, title: "GitLab alternate SSH links", messages: ["Hello"], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Diff D", { exact: true }).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitem", "Commits", { exact: true }).hover();
  const commit = screen.getByRole("menuitem", `Open commit ${sha.slice(0, 7)}`, { exact: true });
  await commit.waitFor();
  await commit.hover();
  const commitUrl = await commit.getAttribute("href");
  await app.screenshot("gitlab-commit-link");
  await screen.getByRole("menuitemradio", /^Feature commit/).tap();
  const selectedCommit = browser.locator(`a[href="${commitUrl}"]`).first();
  await selectedCommit.hover();
  await screen.getByText(commitUrl!, { exact: true }).waitFor();
  await browser.evaluate(async () => {
    await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    await Promise.all(document.getAnimations()
      .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity)
      .map((animation) => animation.finished.catch(() => {})));
    return null;
  });
  await app.screenshot("gitlab-commit-destination");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Control+k");
  await screen.getByRole("combobox").fill("> Link pull request to thread");
  await screen.getByRole("option", "Link pull request to thread", { exact: false }).tap();
  await screen.getByPlaceholder("Pull request URL or #42").fill("4");
  await app.screenshot("gitlab-merge-request-number-resolution");
  // Keep both paths observable before the base's assertion fails.
  await screen.getByRole("button", "Link", { exact: true }).tap();
  await screen.getByRole("dialog", "Link pull request", { exact: true }).waitFor({ state: "hidden" });
  await t3.open("/pull-requests?repository=group%2Fproject&number=4");
  const fallback = screen.getByRole("link", "Open on GitLab", { exact: true });
  await fallback.waitFor();
  await screen.getByRole("status", /^Loading pull requests/).waitFor({ state: "hidden" });
  const mergeRequestUrl = await fallback.getAttribute("href");
  await fallback.hover();
  await app.screenshot("gitlab-merge-request-fallback");
  if (process.env.T3_LINK_EVIDENCE_DIR) {
    const identity = await browser.evaluate(async () => {
      const snapshot = await (await fetch("/api/projects")).json() as {
        projects: Array<{ title: string; repositoryIdentity: {
          provider?: string; canonicalKey: string; webUrl?: string;
          locator: { remoteUrl: string };
        } }>;
      };
      const value = snapshot.projects.find((project) => project.title === "gitlab-altssh")!.repositoryIdentity;
      return { provider: value.provider, canonicalKey: value.canonicalKey,
        remoteUrl: value.locator.remoteUrl, webUrl: value.webUrl ?? null };
    });
    await writeFile(`${process.env.T3_LINK_EVIDENCE_DIR}/${Date.now()}-observed-links.json`,
      JSON.stringify({ identity, commitUrl, mergeRequestUrl }, null, 2));
  }
  await expect({ commitUrl, mergeRequestUrl }).toEqual({
    commitUrl: `https://gitlab.com/group/project/-/commit/${sha}`,
    mergeRequestUrl: "https://gitlab.com/group/project/-/merge_requests/4",
  });
});
