import { spawn } from "node:child_process";
import { readFile, writeFile, utimes, access } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Cause from "effect/Cause";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const exists = async (p: string) => access(p).then(() => true, () => false);
async function until(check: () => Promise<boolean>, timeout = 30000) {
  const end = Date.now() + timeout;
  while (!(await check())) {
    if (Date.now() > end) throw new Error("Setup milestone did not arrive");
    await delay(250);
  }
}

test("A settle script waiting at restart still tears down its resource", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Settle restart demo");
  // Probe and complete a replay turn before starting the two worktree threads.
  await t3.thread({ project, title: "Setup", messages: ["Start"] });
  const { cli } = makeState(T3_HOME);
  const withClient = (use: (client: Effect.Success<ReturnType<typeof rpcClient>>) => any) =>
    runPromise(Effect.scoped(Effect.flatMap(rpcClient(T3_HOME, app.baseUrl ?? ""), use)).pipe(
      Effect.catchCause((cause) => Effect.fail(new Error(Cause.pretty(cause)))),
    ));
  const threads = [];
  const resources = [];
  try {
    for (const name of ["A", "B"]) {
      const result = await runPromise(cli(["thread", "start", project, "Start", "--title", `demo-${name}`, "--worktree", "main", "--branch", `demo-${name}`, "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
      const { threadId } = JSON.parse(result.stdout);
      const shown = await runPromise(cli(["thread", "show", threadId, "--json"]));
      const { thread } = JSON.parse(shown.stdout);
      threads.push({ threadId, path: thread.worktreePath, projectId: thread.projectId });
      const resource = spawn("sleep", ["900"], { stdio: "ignore" });
      resources.push(resource);
      await writeFile(`${thread.worktreePath}/.resource.pid`, String(resource.pid));
    }
    const [a, b] = threads;
    console.log("Both worktree resources running; configuring settle action");
    await withClient((c) => c["server.updateSettings"]({ patch: { projectSettingsOverrides: { [a.projectId]: { defaultProjectScripts: [{ id: "cleanup", name: "Stop worktree resource", command: 'echo "settle script started" >> resource.log; sleep 45; kill "$(cat .resource.pid)"; touch .settle-ran; echo "resource stopped" >> resource.log', icon: "play", runOnSettle: true, runOnWorktreeCreate: false, async: false }] } } } }));
    const settle = (threadId: string) => withClient((c) => c["orchestration.dispatchCommand"]({ type: "thread.settle", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(threadId) }));
    console.log("Opening thread B before settlement");
    await t3.open(b);
    await settle(a.threadId);
    await until(() => exists(`${a.path}/resource.log`));
    await settle(b.threadId);
    await delay(1500);
    if (await exists(`${b.path}/resource.log`)) throw new Error("B started before restart; queue was not blocked");
    const runtimePath = `${T3_HOME}/userdata/server-runtime.json`;
    const before = JSON.parse(await readFile(runtimePath, "utf8"));
    // The app's real dev supervisor stops and restarts the server, keeping its database.
    const now = new Date();
    await utimes(`${APP_DIR}/apps/server/src/bin.ts`, now, now);
    await until(async () => {
      try { return JSON.parse(await readFile(runtimePath, "utf8")).pid !== before.pid; } catch { return false; }
    }, 60000);
    console.log("Server restarted; waiting 155 seconds for queued cleanup");
    await delay(155000);
    await t3.open(b);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = screen.getByLabel("Terminal input");
    await terminal.waitFor();
    const command = 'export PS1="$ "; clear; printf "QUEUED SETTLE ACTION AFTER SERVER RESTART\\n\\nThread B: settled before restart\\n"; if test -f .settle-ran; then echo "Settle action: RAN"; else echo "Settle action: NEVER RAN"; fi; if kill -0 "$(cat .resource.pid)" 2>/dev/null; then echo "Resource: STILL RUNNING"; else echo "Resource: STOPPED"; fi; echo; cat resource.log 2>/dev/null; echo "--- verification complete ---"';
    await terminal.focus();
    await browser.keyboard.type(command);
    await browser.keyboard.press("Enter");
    await delay(1500);
    await app.screenshot("queued-settle-after-restart");
    expect(await exists(`${b.path}/.settle-ran`)).toBe(true);
    expect(resources[1].exitCode !== null || resources[1].signalCode !== null).toBe(true);
  } finally {
    for (const resource of resources) if (resource.exitCode === null && resource.signalCode === null) resource.kill();
  }
});
