/// <reference lib="dom" />
import { ThreadId, ProjectSnapshot } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const CREDIT = "Co-authored-by: Claude <noreply@anthropic.com>";

test("Merging keeps a fenced attribution with a Unicode info string and removes the footer", WEB,
 async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const command = async (program: string, args: string[], cwd?: string) =>
    (await runPromise(run(program, args, { cwd }))).stdout.trim();
  const api = async (endpoint: string, args: string[] = []) => JSON.parse(await command("glab", ["api", endpoint, ...args]));
  const tag = `factory-pr-46649-proof-${Date.now()}`;
  const remote = await api("projects", ["-X", "POST", "-f", `name=${tag}`, "-f", "visibility=private", "-f", "merge_commit_template=%{description}", "-f", "merge_method=merge"]);
  try {
    const project = await t3.project("Unicode merge message", { "README.md": "Base\n" });
    const git = (args: string[]) => command("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", ...args], project);
    await git(["remote", "add", "origin", remote.http_url_to_repo]);
    await git(["push", "-u", "origin", "main"]);
    const thread = await t3.thread({ project, title: "Inspect merge commit", messages: ["Ready"] });
    const origin = app.baseUrl!;
    const environment = await runPromise(environmentId(origin));
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, origin);
      yield* client["terminal.open"]({ threadId: ThreadId.make(thread.threadId), terminalId: "term-1", cwd: project, env: { T3CODE_TERMINAL_SHELL: "/bin/sh", PS1: "$ " } });
    }).pipe(Effect.scoped));
    const projectId = await runPromise(Effect.gen(function* () {
      const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
      const snapshot = yield* HttpClient.execute(HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
      return snapshot.projects.find(p => p.workspaceRoot === project)!.id;
    }).pipe(Effect.provide(FetchHttpClient.layer)));
    await t3.open(`/settings/source-control?machine=${environment}`);
    await screen.getByRole("switch", "Remove agent credits when merging", { exact: true }).tap();
    await app.screenshot("remove-agent-credits-enabled");
    const results: string[] = [];
    for (const [index, separator] of ["\u2028", "\u2029"].entries()) {
      const label = index === 0 ? "U+2028" : "U+2029";
      const branch = `feature-${index}`;
      await git(["checkout", "-b", branch, "main"]);
      await git(["commit", "--allow-empty", "-m", `Feature ${label}`]);
      await git(["push", "origin", branch]);
      const description = `\x60\x60\x60text${separator}extra\n${CREDIT}\n\x60\x60\x60\n\n${CREDIT}`;
      const mr = await api(`projects/${remote.id}/merge_requests`, ["-X", "POST", "-f", `source_branch=${branch}`, "-f", "target_branch=main", "-f", `title=Preserve ${label} fenced example`, "-f", `description=${description}`]);
      await git(["checkout", "main"]);
      const query = new URLSearchParams({ repository: remote.path_with_namespace, number: String(mr.iid), selectedProjectId: projectId, selectedEnvironmentId: environment, selectedHost: "gitlab.com" });
      await t3.open(`/pull-requests?${query}`);
      const merge = screen.getByRole("button", "Merge", { exact: true });
      await merge.waitFor({ timeout: 60_000 });
      await browser.evaluate(async () => {
        const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find(b => b.getAttribute('aria-label') === 'Merge')!;
        button.click();
        await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
        const confirm = [...document.querySelectorAll<HTMLButtonElement>('button')].find(b => b.getAttribute('aria-label') === 'Confirm merge?');
        if (!confirm) throw new Error('Merge confirmation did not arm');
        confirm.click();
      });
      await screen.getByText("Merged", { exact: true }).first().waitFor({ timeout: 60_000 });
      await app.screenshot(`merged-${label}`);
      await git(["fetch", "origin", "main"]);
      const mergeSha = await git(["rev-parse", "origin/main"]);
      const message = await git(["show", "-s", "--format=%B", mergeSha]);
      results.push(`${label}: ${message.trim()}`);
      // Display the real GitLab commit in the app's terminal, with separators escaped for legibility.
      await t3.open(thread);
      await screen.getByRole("button", "Toggle terminal drawer").tap();
      await screen.getByLabel("Terminal input").waitFor();
      await runPromise(Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, origin);
        yield* client["terminal.write"]({ threadId: ThreadId.make(thread.threadId), terminalId: "term-1", data: `PS1='$ '; clear; git show -s --format='%H%n%P%n%B' ${mergeSha} | python3 -c 'import sys; s=sys.stdin.read().replace(chr(0x2028), "<U+2028>").replace(chr(0x2029), "<U+2029>").split("\\n"); print("Merge commit: "+s[0][:8]); print("Parents: "+str(len(s[1].split()))); print("Message:"); print("\\n".join(s[2:]))'\r` });
      }).pipe(Effect.scoped));
      // Wait for the terminal's copy buffer to contain the command result before capture.
      await expect.poll(async () => {
        await browser.evaluate(() => { document.body.dataset.copied = ""; document.addEventListener("copy", e => { document.body.dataset.copied = e.clipboardData?.getData("text/plain") ?? ""; }, { once: true }); });
        await screen.getByLabel("Terminal input").focus();
        await browser.keyboard.press("Control+Shift+A");
        await browser.keyboard.press("Control+Shift+C");
        return browser.evaluate(() => document.body.dataset.copied ?? "");
      }, { timeout: 30_000 }).toContain(`Merge commit: ${mergeSha.slice(0, 8)}\nParents: 2`);
      const canvas = await browser.evaluate(() => {
        const r = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector('canvas')!.getBoundingClientRect();
        return { x: r.x + r.width - 30, y: r.y + r.height - 20 };
      });
      await browser.mouse.move(canvas.x, canvas.y);
      await browser.mouse.down();
      await browser.mouse.up();
      await app.screenshot(`commit-message-${label}`);
      await screen.getByRole("button", "Toggle terminal drawer").tap();
    }
    expect(results).toEqual(["\u2028", "\u2029"].map((separator, index) => `${index === 0 ? "U+2028" : "U+2029"}: \x60\x60\x60text${separator}extra\n${CREDIT}\n\x60\x60\x60`));
  } finally {
    await command("glab", ["api", `projects/${remote.id}`, "-X", "DELETE"]).catch(() => {});
  }
});
