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

test("Cancelling branch creation frees the branch name", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" && provider.models.some(model => model.slug === "showcase"));
      }),
      Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const overview = await t3.thread({ project, title: "Branch cancellation evidence", messages: ["hello"], model: "showcase" });
  await t3.open(overview);
  await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: project }))).stdout.trim();
  const connected = Promise.withResolvers<void>();
  const sockets = new Set<net.Socket>();
  const gate = net.createServer(socket => { sockets.add(socket); connected.resolve(); });
  await new Promise<void>(resolve => gate.listen(0, "127.0.0.1", resolve));
  using _gate = { [Symbol.dispose]() { for (const socket of sockets) socket.destroy(); gate.close(); } };
  const address = gate.address();
  if (!address || typeof address === "string") throw new Error("No hook gate port");
  await fs.writeFile(`${project}/.git/gate.cjs`, `const fs = require('node:fs');
const input = fs.readFileSync(0, 'utf8');
if (process.argv[2] === 'committed' && input.split('\\n').some(l => /^0+ [0-9a-f]+ refs\\/heads\\/worktree-topic$/.test(l)) && !fs.existsSync('.git/gate-used')) {
 fs.writeFileSync('.git/gate-used', 'created');
 const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.resume();
}
`);
  await fs.writeFile(`${project}/.git/hooks/reference-transaction`, `#!/bin/sh\nexec '${process.execPath}' '${project}/.git/gate.cjs' "$@"\n`, { mode: 0o755 });
  const { cli } = makeState(T3_HOME);
  const args = ["thread", "start", project, "hello2", "--worktree", "main", "--branch", "worktree-topic", "--provider", "devReplay", "--model", "showcase", "--json"];
  const started = JSON.parse((await runPromise(cli(args))).stdout);
  await connected.promise;
  const during = await git("branch", "--list", "worktree-topic");
  if (!during.includes("worktree-topic")) throw new Error("Hook did not hold a created branch");
  await t3.open(started);
  await screen.getByRole("button", "Cancel", { exact: true }).waitFor();
  await app.screenshot("branch-creation-blocked");
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await screen.getByText("Worktree setup cancelled", { exact: true }).first().waitFor();
  for (const socket of sockets) socket.end();
  await app.screenshot("setup-cancelled");
  const remaining = await git("for-each-ref", "--format=%(refname)", "refs/heads/worktree-topic");
  const retry = await runPromise(cli(args, [0, 1]));
  const report = ["BRANCH CREATION CANCELLATION", "Hook blocked after branch creation; branch exists: true", "Clicked Cancel before Git timeout; app showed cancelled.", "Released the hook.", "", `Branch after cancellation: ${remaining || "(absent)"}`, "", `Retry same branch name — exit code: ${retry.exitCode}`, retry.exitCode === 0 ? "New thread created successfully." : 'Branch "worktree-topic" already exists. No thread was created.', "END OF EVIDENCE"].join("\n");
  await fs.writeFile(`${project}/cancellation-evidence.txt`, report);
  await t3.open(overview);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const readyDeadline = Date.now() + 15000;
  while (Date.now() < readyDeadline) {
    await terminal.focus();
    await browser.keyboard.type("printf ready > .git/terminal-ready");
    await browser.keyboard.press("Enter");
    await new Promise(r => setTimeout(r, 200));
    if (await fs.readFile(`${project}/.git/terminal-ready`, "utf8").catch(() => "") === "ready") break;
  }
  await terminal.focus();
  await browser.keyboard.type("export PS1='$ '; clear; cat cancellation-evidence.txt");
  await browser.keyboard.press("Enter");
  // The sentinel confirms that the real terminal rendered the evidence file.
  const terminalText = async () => {
    await browser.evaluate(() => { document.body.dataset.copy = ""; window.addEventListener("copy", e => { document.body.dataset.copy = e.clipboardData?.getData("text/plain") ?? ""; }, { once: true }); return null; });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.copy ?? "");
  };
  const deadline = Date.now() + 15000;
  while (!(await terminalText()).includes("END OF EVIDENCE") && Date.now() < deadline) await new Promise(r => setTimeout(r, 100));

  await app.screenshot("branch-name-reuse");
  await expect(remaining).toBe("");
  await expect(retry.exitCode).toBe(0);
});
