/// <reference lib="dom" />
import { expect } from "e2e";
import { DatabaseSync } from "node:sqlite";
import { writeFileSync, existsSync, chmodSync } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const GIT_CAPTURE_GATE = "#!/usr/bin/python3\nimport os, sys, sqlite3, time, pathlib\nargs=sys.argv[1:]\nif 'commit-tree' in args or 'write-tree' in args:\n    gd=pathlib.Path(args[args.index('-C')+1] if '-C' in args else os.getcwd())/'.git'\n    if (gd/'proof-db').exists() and (gd/'hold-capture').exists():\n        try:\n            db=sqlite3.connect('file:'+ (gd/'proof-db').read_text()+'?mode=ro',uri=True)\n            waiting=db.execute(\"select count(*) from orchestration_v2_projection_runs where status='waiting'\").fetchone()[0]\n            db.close()\n            if waiting:\n                (gd/'capture-paused').write_text('Git checkpoint capture is paused before '+args[args.index('commit-tree') if 'commit-tree' in args else args.index('write-tree')])\n                for i in range(1200):\n                    if (gd/'release-capture').exists(): break\n                    time.sleep(.1)\n        except Exception: pass\nos.execv('/usr/bin/git',['/usr/bin/git']+args)\n";

test("Deleting a waiting turn preserves cancellation after checkpoint capture", WEB, async ({t3, app, screen, browser}) => {
  writeFileSync(`${T3_HOME}/bin/git`, GIT_CAPTURE_GATE);
  chmodSync(`${T3_HOME}/bin/git`, 0o755);
  const project = await t3.project("checkpoint-demo", {"README.md":"Synthetic checkpoint cancellation example\n"});
  const thread = await t3.thread({project, title:"Checkpoint cancellation", messages:["first"]});
  const dbPath = `${T3_HOME}/userdata/statev2.sqlite`;
  const read = () => {
    const db = new DatabaseSync(dbPath, {readOnly:true});
    try {
      const row = db.prepare("SELECT payload_json FROM orchestration_v2_projection_runs WHERE thread_id=? ORDER BY ordinal DESC LIMIT 1").get(thread.threadId) as {payload_json:string};
      const run = JSON.parse(row.payload_json);
      const node = db.prepare("SELECT status FROM orchestration_v2_projection_nodes WHERE node_id=?").get(run.rootNodeId) as {status:string};
      const th = db.prepare("SELECT deleted_at FROM orchestration_v2_projection_threads WHERE thread_id=?").get(thread.threadId) as {deleted_at:string|null};
      return {status:run.status, completedAt:run.completedAt, checkpointAttached:run.checkpointId!==null, rootStatus:node.status, threadDeleted:th.deleted_at!==null};
    } finally {db.close();}
  };
  const waitFor = async (check:()=>boolean, label:string) => {
    const until=Date.now()+90000;
    while(!check()) { if(Date.now()>until) throw new Error(`STEP_TIMEOUT: ${label}`); await new Promise(r=>setTimeout(r,100)); }
  };
  const show = async (label:string, data:unknown) => browser.evaluate(({label,data})=>{
    document.getElementById("checkpoint-proof")?.remove();
    const p=document.createElement("pre"); p.id="checkpoint-proof";
    p.style.cssText="position:fixed;bottom:20px;right:20px;z-index:2147483647;background:#101820;color:#e8f0f7;padding:24px;border:2px solid #70a0b0;border-radius:8px;font:18px/1.6 monospace;max-width:650px;white-space:pre-wrap";
    p.textContent=`Read-only server database observation\n${label}\n\n${JSON.stringify(data,null,2)}\n\nSynthetic data • real server • Replay provider`;
    document.body.append(p); return null;
  },{label,data});
  await t3.open(thread);
  writeFileSync(`${project}/.git/proof-db`, dbPath);
  writeFileSync(`${project}/.git/hold-capture`, "1");
  await screen.getByRole("textbox").fill("second");
  await screen.getByRole("textbox").press("Enter");
  await waitFor(()=>existsSync(`${project}/.git/capture-paused`),"Git checkpoint capture in flight");
  await show("Capture in flight",read());
  await app.screenshot("capture-in-flight");
  await browser.evaluate(()=>{document.getElementById("checkpoint-proof")?.remove(); return null;});
  await screen.getByRole("button", "Thread actions for Checkpoint cancellation").tap();
  await screen.getByRole("menuitem", "Delete", {exact:true}).tap();
  await screen.getByRole("button", "Confirm", {exact:true}).tap();
  await waitFor(()=>read().status==="cancelled","thread deletion commits cancellation");
  const cancelled=read();
  await show("Deletion committed while capture is paused",cancelled);
  await app.screenshot("cancelled-during-capture");
  writeFileSync(`${project}/.git/release-capture`, "1");
  await waitFor(()=>read().checkpointAttached,"captured rollback checkpoint attached");
  const final=read();
  await show("After Git checkpoint capture finishes",{cancelledDuringCapture:cancelled,afterCapture:final,completionTimestampPreserved:final.completedAt===cancelled.completedAt});
  await app.screenshot("after-capture");
  expect(final).toEqual({...cancelled, checkpointAttached:true});
});
