import * as NodeNet from "node:net";
import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

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

const decodeThread = Schema.decodeUnknownSync(
  Schema.fromJsonString(Schema.Struct({ threadId: ThreadId })),
);

test(
  "Continuing after stopping the checkout hook initializes its submodule",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("demo");
    const dependency = `${project}/../dependency`;
    const fs = await runPromise(FileSystem.FileSystem);
    const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
    const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
    await runPromise(fs.makeDirectory(dependency));
    await git(dependency, "init", "--initial-branch=main");
    await runPromise(fs.writeFileString(`${dependency}/contents.txt`, "dependency contents"));
    await git(dependency, "add", "contents.txt");
    await git(dependency, ...author, "commit", "-m", "Dependency");
    await git(project, "-c", "protocol.file.allow=always", "submodule", "add", dependency, "dep");
    await git(project, ...author, "commit", "-m", "Add dependency");
    const { cli } = makeState(T3_HOME);
    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(({ slug }) => slug === "multi-turn"),
            );
          }),
          Stream.runHead,
        );
      }).pipe(Effect.scoped, Effect.timeout("30 seconds")),
    );
    const started = await runPromise(
      cli([
        "thread",
        "start",
        project,
        "Start",
        "--worktree",
        "main",
        "--provider",
        "devReplay",
        "--model",
        "multi-turn",
        "--wait",
        "--json",
      ]),
    );
    const thread = decodeThread(started.stdout);
    const worktreePath = await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl);
        const { thread: projection } = yield* client["orchestration.getThreadProjection"](thread);
        if (!projection.worktreePath) throw new Error("The thread has no linked worktree");
        return projection.worktreePath;
      }).pipe(Effect.scoped),
    );
    await git(worktreePath, "-c", "protocol.file.allow=always", "submodule", "update", "--init");
    if (!(await runPromise(fs.exists(`${worktreePath}/dep/contents.txt`)))) {
      throw new Error("The demo submodule could not be initialized");
    }
    await git(project, "worktree", "remove", "--force", worktreePath);
    const realGit = (await runPromise(run("sh", ["-c", "command -v git"]))).stdout.trim();
    const connected = Promise.withResolvers<void>();
    const disconnected = Promise.withResolvers<void>();
    const sockets = new Set<NodeNet.Socket>();
    const gate = NodeNet.createServer((socket) => {
      sockets.add(socket);
      connected.resolve();
      socket.once("close", () => disconnected.resolve());
      socket.resume();
    });
    using _gate = {
      [Symbol.dispose]() {
        for (const socket of sockets) socket.destroy();
        gate.close();
      },
    };
    await new Promise<void>((resolve, reject) => {
      gate.once("error", reject);
      gate.listen(0, "127.0.0.1", resolve);
    });
    const address = gate.address();
    if (address === null || typeof address === "string") throw new Error("Missing Git gate port");
    const hook = `${project}/.git/hooks/post-checkout`;
    await runPromise(fs.writeFileString(hook, `#!/usr/bin/env node\nimport { connect } from "node:net"; connect(${address.port}, "127.0.0.1").resume();\n`));
    await runPromise(fs.chmod(hook, 0o755));
    const wrapper = writeFakeCli({
      directory: `${T3_HOME}/bin`,
      name: "git",
      source: `
        import { spawnSync } from "node:child_process";
        const args = process.argv.slice(2);
        const update = args.some((arg, index) => arg === "submodule" && args[index + 1] === "update");
        const options = update ? ["-c", "protocol.file.allow=always"] : [];
        process.exit(spawnSync(${JSON.stringify(realGit)}, [...options, ...args], { stdio: "inherit" }).status ?? 1);
      `,
    });
    try {
      await t3.open(thread);
      const composer = screen.getByRole("textbox");
      await composer.waitFor({ timeout: 120_000 });
      await composer.fill("Continue here");
      await composer.press("Enter");
      await connected.promise;
      const stop = screen.getByRole("button", "Stop generation");
      await stop.tap();
      await disconnected.promise;
      if (!(await runPromise(fs.exists(`${worktreePath}/.git`)))) {
        throw new Error("Stopping the turn did not leave the checkout in place");
      }
      await runPromise(fs.remove(hook));

      await runPromise(cli(["thread", "send", thread.threadId, "Try again", "--wait", "--json"]));
      await screen.getByText("Try again", { exact: true }).waitFor();
      await app.screenshot("after-stopped-checkout-hook");
      expect(await runPromise(fs.exists(`${worktreePath}/dep/contents.txt`))).toBe(true);
    } finally {
      await runPromise(fs.remove(wrapper, { force: true }));
    }
  },
);
