import { execFileSync } from "node:child_process";
import { join } from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A queued follow-up starts after checkpoint capture gives up", WEB, async ({ t3, app, screen }) => {
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { defaultRuntimeMode: "approval-required" } });
  }).pipe(Effect.scoped));
  const project = await t3.project("checkpoint-demo", { "file.txt": "Before change\n" });
  const thread = await t3.thread({ project, title: "Checkpoint recovery", messages: ["Change the file"], model: "approval" });
  await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Review the change"]));
  await t3.open(thread);
  const queued = screen.getByRole("button", "Edit queued message");
  await queued.waitFor({ state: "visible", timeout: 60_000 });
  await app.screenshot("follow-up-queued");
  const sql = (query: string) => execFileSync("sqlite3", [join(T3_HOME, "userdata/statev2.sqlite"), query], { encoding: "utf8" }).trim();
  sql(`CREATE TRIGGER reject_first_checkpoint BEFORE INSERT ON orchestration_v2_projection_checkpoints WHEN NEW.thread_id = '${thread.threadId}' AND NEW.app_run_ordinal = 1 BEGIN SELECT RAISE(ABORT, 'Evidence: checkpoint persistence unavailable'); END;`);
  await screen.getByRole("button", "Approve", { exact: true }).tap();
  const deadline = Date.now() + 60_000;
  while (!sql("SELECT count(*) FROM orchestration_v2_effect_outbox WHERE effect_type = 'checkpoint.capture' AND status = 'failed';").match(/^[1-9]/)) {
    if (Date.now() > deadline) throw new Error("Checkpoint capture did not exhaust retries");
    await new Promise(resolve => setTimeout(resolve, 250));
  }
  await new Promise(resolve => setTimeout(resolve, 10_000));
  await app.screenshot("after-checkpoint-capture-failed");
  await expect(queued).toHaveCount(0, { timeout: 10_000 });
});
