import * as fs from "node:fs/promises";
import * as NodeNet from "node:net";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";

import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

const decodeLaunched = Schema.decodeUnknownEffect(
  Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })),
);

test(
  "Cancelling worktree setup during its post-checkout hook removes the new worktree",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo");
    const git = (...args: ReadonlyArray<string>) =>
      runPromise(run("git", args, { cwd: project })).then(({ stdout }) => stdout);
    const otherPath = `${project}-other-creator`;
    await git("worktree", "add", "-b", "other-creator", otherPath, "main");
    const connected = Promise.withResolvers<void>();
    const sockets = new Set<NodeNet.Socket>();
    const server = NodeNet.createServer((socket) => {
      sockets.add(socket);
      connected.resolve();
    });
    using _gateServer = {
      [Symbol.dispose]() {
        for (const socket of sockets) socket.destroy();
        server.close();
      },
    };
    await new Promise<void>((resolve, reject) => {
      server.once("error", reject);
      server.listen(0, "127.0.0.1", resolve);
    });
    const address = server.address();
    if (address === null || typeof address === "string") throw new Error("Missing hook gate port");
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const hook = `${project}/.git/hooks/post-checkout`;
        const gate = `${project}/hook-gate.cjs`;
        yield* fs.writeFileString(
          gate,
          `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.on('connect', () => process.stderr.write('Updating files:  50% (1/1000)\\n')); s.resume();`,
        );
        yield* fs.writeFileString(
          hook,
          `#!/bin/sh\nexec "${process.execPath}" "${gate}"\n`,
        );
        yield* fs.chmod(hook, 0o755);
      }),
    );
    const started = await runPromise(
      run(
        process.execPath,
        [
          "apps/server/src/bin.ts",
          "thread",
          "start",
          project,
          "hello",
          "--worktree",
          "main",
          "--provider",
          "devReplay",
          "--model",
          "showcase",
          "--json",
          "--base-dir",
          T3_HOME,
        ],
        { cwd: APP_DIR, env: { PATH: process.env.PATH, HOME: process.env.HOME } },
      ).pipe(Effect.flatMap(({ stdout }) => decodeLaunched(stdout))),
    );

    await connected.promise;
    const inFlight = await git("worktree", "list", "--porcelain");
    const setupEntry = inFlight.split("\n\n").find((entry) => entry.includes("branch refs/heads/t3/"));
    if (!setupEntry) throw new Error("Missing setup's registered worktree");
    const setupPath = /^worktree (.+)$/m.exec(setupEntry)![1]!;
    const setupBranch = /^branch refs\/heads\/(.+)$/m.exec(setupEntry)![1]!;
    await t3.open(started);
    await screen.getByText("50%", { exact: true }).waitFor();
    await app.screenshot("hook-running");
    await screen.getByRole("button", "Cancel").tap();
    await screen.getByText("Worktree setup cancelled", { exact: true }).waitFor();

    let reused = false;
    try {
      await expect.poll(async () => {
        const entries = await git("worktree", "list", "--porcelain");
        const branch = await git("branch", "--list", setupBranch);
        const directoryExists = await fs.access(setupPath).then(() => true, () => false);
        return {
          worktrees: entries.match(/^worktree /gm)?.length,
          setupBranchPresent: branch.trim().length > 0,
          setupDirectoryPresent: directoryExists,
          otherCreatorPreserved: entries.includes(`worktree ${otherPath}\n`) &&
            await fs.readFile(`${otherPath}/README.md`, "utf8").then(() => true, () => false),
        };
      }).toEqual({ worktrees: 2, setupBranchPresent: false, setupDirectoryPresent: false, otherCreatorPreserved: true });
      // Disable only this fixture's blocking hook before checking that Git can reuse both names.
      await fs.chmod(`${project}/.git/hooks/post-checkout`, 0o644);
      await git("worktree", "add", "-b", setupBranch, setupPath, "main");
      reused = true;
      await git("worktree", "remove", "--force", setupPath);
      await git("branch", "-D", setupBranch);
    } finally {
      const entries = await git("worktree", "list", "--porcelain");
      const branches = await git("branch", "--list");
      const inspection = [
        "Evidence driver — live Git inspection after Cancel",
        "",
        "$ git worktree list --porcelain (paths anonymized)",
        entries.replaceAll(setupPath, "<cancelled-setup>").replaceAll(project, "<project>").replaceAll(setupBranch, "t3/<setup>").split("\n").filter((line) => line && !line.startsWith("HEAD ")).join("\n"),
        "$ git branch --list",
        branches.replaceAll(setupBranch, "t3/<setup>"),
        `Cancelled directory exists: ${await fs.access(setupPath).then(() => true, () => false)}`,
        `Another creator preserved: ${entries.includes(`worktree ${otherPath}\n`)}`,
        `Cancelled path + branch reused successfully: ${reused}`,
      ].join("\n");
      await browser.evaluate((text) => {
        const panel = document.createElement("pre");
        panel.textContent = text;
        panel.style.cssText = "position:fixed;z-index:99999;right:20px;bottom:20px;width:650px;box-sizing:border-box;margin:0;padding:18px;background:#102033;color:#e4f0ff;border:2px solid #527ca5;border-radius:10px;font:13px/1.4 monospace;white-space:pre-wrap;box-shadow:0 4px 16px #0004";
        document.body.append(panel);
      }, inspection);
      await app.screenshot("after-cancel-git-inspection");
    }
  },
);
