import * as net from "node:net";
import { randomUUID } from "node:crypto";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as C from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A stopped worktree setup can retry and release its held message without a stale interruption", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Stopped setup demo");
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  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 cleanup = {[Symbol.dispose]() { for (const socket of sockets) socket.destroy(); gate.close(); }};
  const port = (gate.address() as net.AddressInfo).port;
  await git("remote", "add", "origin", `git://127.0.0.1:${port}/fixture.git`);
  await git("update-ref", "refs/remotes/origin/main", "HEAD");
  const {cli} = makeState(T3_HOME);
  const token = (await runPromise(cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
  const snapshot = await (await fetch(`${app.baseUrl}/api/projects`, {headers: {authorization: `Bearer ${token}`}})).json();
  const projectId = snapshot.projects.find((p: {workspaceRoot: string}) => p.workspaceRoot === project).id;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const launched = yield* client["orchestration.launchThread"]({
      commandId: C.CommandId.make(randomUUID()), projectId,
      title: "Stopped setup retry", creationSource: "web",
      modelSelection: {instanceId: C.ProviderInstanceId.make("devReplay"), model: "multi-turn"},
      runtimeMode: "full-access", interactionMode: "default",
      workspaceStrategy: {type: "worktree", baseRef: "origin/main", startFromOrigin: true, branch: "recovery-demo"},
      initialMessage: {text: "First message", attachments: []},
    });
    yield* Effect.promise(async () => {
      await connected.promise;
      await t3.open(launched);
      const stop = screen.getByRole("button", "Stop generation");
      await stop.waitFor({timeout: 60000});
      await stop.tap();
      await screen.getByText("Run interrupted before provider start", {exact: false}).first().waitFor();
      const sent = JSON.parse((await runPromise(cli(["thread", "send", launched.threadId, "Follow-up sent after Stop", "--json"]))).stdout);
      console.log("AUTO_SEND_EVIDENCE " + JSON.stringify({delivery: sent.delivery, held: sent.held, next: sent.next}));
      await screen.getByText("1 queued", {exact: false}).first().waitFor();
      await app.screenshot("held-after-stop");
      await screen.getByRole("button", "Send now", {exact: true}).first().tap();
      await app.screenshot("after-send-now");
      // Restore a usable local origin so retry executes a real fetch and worktree creation.
      await git("remote", "set-url", "origin", project);
      const retry = screen.getByRole("button", "Retry", {exact: true});
      await app.screenshot("retry-available");
      await expect(retry).toBeVisible();
      await retry.tap();
      await screen.getByText("first fixture turn complete", {exact: false}).first().waitFor({timeout: 60000});
      await screen.getByText("second fixture turn complete", {exact: false}).first().waitFor({timeout: 60000});
      await stop.waitFor({state: "hidden", timeout: 60000});
      await screen.getByText("1 queued", {exact: false}).first().waitFor({state: "hidden"});
      await expect(screen.getByText("Run interrupted before provider start", {exact: false})).not.toBeVisible();
      await new Promise(resolve => setTimeout(resolve, 5000));
      await app.screenshot("retry-completed-and-queue-released");
    });
  }).pipe(Effect.scoped));
});
