// @effect-diagnostics nodeBuiltinImport:off -- Reproduce a real slow Git checkpoint with sparse untracked files and observe its persisted milestones read-only.
import { open } from "node:fs/promises";
import { DatabaseSync } from "node:sqlite";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

async function largeFile(path: string, gb: number) {
  const file = await open(path, "w");
  await file.truncate(gb * 1024 ** 3);
  await file.close();
}

test("Accepted Stop during final checkpoint leaves the turn interrupted", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("checkpoint-stop");
  await largeFile(`${project}/first-untracked.bin`, 3);
  const thread = await t3.thread({ project, title: "Stop while saving checkpoint", messages: ["hello"], model: "multi-turn" });
  await largeFile(`${project}/second-untracked.bin`, 6);
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ timeout: 60000 });
  const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, { readOnly: true });
  const latest = () => db.prepare("SELECT status, payload_json FROM orchestration_v2_projection_runs WHERE thread_id = ? ORDER BY ordinal DESC LIMIT 1").get(thread.threadId) as { status: string; payload_json: string };
  const waitFor = async (ready: () => boolean, label: string) => {
    for (let i = 0; i < 1800; i++) {
      if (ready()) return;
      await setTimeout(100);
    }
    throw new Error(`Timed out waiting for ${label}`);
  };
  try {
    await screen.getByRole("textbox").fill("second message");
    await screen.getByRole("textbox").press("Enter");
    await waitFor(() => {
      const row = db.prepare("SELECT status FROM orchestration_v2_projection_runs WHERE thread_id = ? AND ordinal = 2").get(thread.threadId) as { status: string } | undefined;
      return row?.status === "waiting";
    }, "second turn's checkpoint capture");
    await app.screenshot("reply-arrived-checkpoint-saving");
    await screen.getByRole("button", "Stop generation").tap();
    await waitFor(() => ["completed", "interrupted", "cancelled", "failed"].includes(latest().status), "terminal run");
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
    await app.screenshot("after-accepted-stop");
    expect(latest().status, "An accepted Stop must finalize the run as interrupted").toBe("interrupted");
    await expect(screen.getByText("Run interrupted", { exact: true }).last()).toBeVisible();
  } finally {
    db.close();
  }
});
