import { randomBytes } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Retry keeps source worktree setup stopped during a move", WEB, async ({ t3, app, screen }) => {
  const repository = { ".git/config": '[remote "origin"]\nurl = https://github.com/scenario/demo.git\n' };
  const source = await t3.project("demo", repository);
  const origin = app.baseUrl ?? "";
  const server = startSecondServer(origin);
  try {
    const { host } = await server.ready;
    const remote = makeState(SECOND_HOME);
    const destination = await remote.state.project("demo-destination", repository);
    await runPromise(Effect.gen(function* () {
      yield* run("git", ["fetch", "-u", source, "+main:main"], { cwd: destination });
      for (const cwd of [source, destination]) {
        yield* run("git", ["config", `url.${source}.insteadOf`, "https://github.com/scenario/demo.git"], { cwd });
        yield* run("git", ["config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"], { cwd });
      }
      const primary = yield* rpcClient(T3_HOME, origin);
      const secondary = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, secondary]) {
        yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      }
      yield* primary["server.updateSettings"]({ patch: { defaultProjectScripts: [{ id: "setup", name: "Setup", command: "echo setup-started; sleep 900", icon: "play", runOnWorktreeCreate: true, async: false }] } });
      const pairing = yield* remote.cli(["auth", "pairing", "create", "--json"]);
      const { credential } = JSON.parse(pairing.stdout);
      yield* primary["peerLinks.link"]({ url: host, pairingCode: credential, access: "full-access", label: "Destination" });
    }).pipe(Effect.scoped));
    const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", source, "Say hello", "--title", "Stopped setup", "--worktree", "main", "--provider", "devReplay", "--model", "showcase", "--json"]));
    const thread = JSON.parse(started.stdout);
    await t3.open(thread);
    await screen.getByText("setup-started", { exact: false }).first().waitFor({ timeout: 60_000 });
    await screen.getByRole("button", "Stop generation").tap();
    const retry = screen.getByRole("button", "Retry", { exact: true });
    await retry.waitFor({ timeout: 30_000 });
    // A real untracked asset keeps the move visible long enough to capture its source state.
    await writeFile(`${source}/demo-asset.bin`, randomBytes(24 * 1024 * 1024));
    await screen.getByRole("button", "Thread actions for Stopped setup").tap();
    await screen.getByRole("menuitem", "Continue on another machine…").tap();
    await screen.getByRole("button", /^Move to /).tap();
    await screen.getByText(/^Moving to /).waitFor();
    await retry.tap();
    await app.screenshot("retry-during-thread-move");
    const projection = await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      return yield* primary["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) });
    }).pipe(Effect.scoped));
    expect(projection.runs.map(run => run.status), "Source workspace preparation remains stopped during/after departure").not.toContain("preparing");
  } finally {
    await server.stop();
  }
});
