/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as http from "node:http";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Git truncation drops split emoji and preserves complete emoji", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("emoji-boundaries", { "README.md": "Initial\n" });
  const thread = await t3.thread({ project, title: "Emoji boundary proof", messages: ["Start"] });
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git(["config", "user.name", "Scenario"]);
  await git(["config", "user.email", "scenario@example.invalid"]);
  await git(["config", "core.hooksPath", ".git/hooks"]);
  await browser.setViewport({ width: 1920, height: 1080 });
  await t3.open(thread);
  const results: { label: string; actual: string; expected: string }[] = [];
  let generatedSubject = "a".repeat(71) + "😀bb";
  const endpoint = http.createServer(async (req, res) => {
    for await (const _ of req) { /* drain request */ }
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ choices: [{ finish_reason: "stop", message: { content: JSON.stringify({ subject: generatedSubject, body: "" }) } }] }));
  });
  await new Promise<void>((resolve) => endpoint.listen(0, "127.0.0.1", resolve));
  const port = (endpoint.address() as { port: number }).port;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {
      textGenerators: { "boundary-generator": { kind: "openaiCompatible", label: "Boundary fixture", baseUrl: `http://127.0.0.1:${port}`, apiKey: "", enabled: true } },
      textGenerationModelSelection: { instanceId: "boundary-generator", model: "boundary" },
    } });
  }).pipe(Effect.scoped));
  const readStatus = () => browser.evaluate(() => {
    const row = [...document.querySelectorAll('[role="status"]')].find(el => el.textContent?.includes("Committed "));
    return row?.querySelectorAll("p")[1]?.textContent ?? "MISSING";
  });
  const captureSuccess = async (label: string, expected: string) => {
    await screen.getByText(/^Committed [a-f0-9]+$/).waitFor({ timeout: 15_000 });
    const actual = await readStatus();
    // Capture aid: wrap the app's existing paragraph so the full server text is visible.
    await browser.evaluate(() => {
      const row = [...document.querySelectorAll('[role="status"]')].find(el => el.textContent?.includes("Committed "));
      const description = row?.querySelectorAll("p")[1];
      if (description) {
        Object.assign(description.style, { whiteSpace: "normal", overflow: "visible", overflowWrap: "anywhere", textOverflow: "clip" });
        description.scrollLeft = 0;
      }
      return Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => null))).then(() => null);
    });
    await app.screenshot(label);
    results.push({ label, actual, expected });
    await browser.keyboard.press("Escape");
  };
  const commit = async (label: string, message: string) => {
    await fs.writeFile(`${project}/README.md`, label + "\n");
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill(message);
    await screen.getByRole("button", "Commit", { exact: true }).tap();
  };
  try {
    const hook = `${project}/.git/hooks/pre-commit`;
    const gate = `${project}/.git/release-hook`;
    // Hold the hook open until its output has been captured, then release it from the scenario.
    await fs.writeFile(hook, `#!/usr/bin/env node\nimport * as fs from 'node:fs';\nconsole.log('${"a".repeat(499)}😀bbbb');\nfs.watch('${project}/.git', () => { if (fs.existsSync('${gate}')) process.exit(0); });\n`);
    await fs.chmod(hook, 0o755);
    await commit("Split toast and hook", "a".repeat(68) + "😀bbbb");
    await screen.getByText(/^a{499}/).waitFor({ timeout: 15_000 });
    const hookText = await browser.evaluate(() => [...document.querySelectorAll('[role="status"] p')].find(el => el.textContent?.startsWith("a".repeat(499)))?.textContent ?? "MISSING");
    await browser.evaluate(() => {
      const output = [...document.querySelectorAll('[role="status"] p')].find(el => el.textContent?.startsWith("a".repeat(499)));
      if (output) {
        Object.assign((output as HTMLElement).style, { whiteSpace: "normal", overflow: "visible", overflowWrap: "anywhere", textOverflow: "clip" });
        output.scrollLeft = 0;
      }
      return Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => null))).then(() => null);
    });
    await app.screenshot("split-hook-end");
    results.push({ label: "split hook", actual: hookText, expected: "a".repeat(499) });
    await fs.writeFile(gate, "release");
    await captureSuccess("split-toast-end", "a".repeat(68) + "...");
    await fs.writeFile(hook, "#!/bin/sh\nexit 0\n");
    await commit("Complete emoji fits toast", "a".repeat(67) + "😀bbbb");
    await captureSuccess("complete-emoji-end", "a".repeat(67) + "😀...");
    await commit("Generated split emoji", "");
    await captureSuccess("generated-subject-end", "a".repeat(71));
    const generated = await git(["log", "-1", "--format=%s"]);
    results.push({ label: "generated subject", actual: generated.stdout.trim(), expected: "a".repeat(71) });
    // A model's already malformed 72-unit response passes the shared <=72 fast path.
    // This reaches GitManager's sanitization rather than the shared grapheme-aware longer cut.
    generatedSubject = "a".repeat(71) + "\ud83d";
    await commit("Generated 72 unit malformed response", "");
    await captureSuccess("generated-72-unit-sanitizer", "a".repeat(71));
    generatedSubject = "\ud83d";
    await commit("Generated empty result fallback", "");
    await captureSuccess("generated-fallback-end", "Update project files");
    // All cases are captured on both sides before reporting the broken behavior.
    expect(results).toEqual(results.map(row => ({ ...row, actual: row.expected })));
  } finally {
    endpoint.close();
  }
});
