/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Offline snooze survives a reconnect snapshot that omits the older settled thread", WEB, async ({ t3, app, browser, screen }) => {
  const rpc = (job: (client: any) => any) => runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* job(client);
  })));
  await rpc((client) => client["server.refreshProviders"]({ instanceId: "devReplay", fresh: true, refreshModels: true }));
  const project = await t3.project("demo");
  const rows = [];
  rows.push(await t3.thread({ project, title: "Row 0", model: "default", messages: ["first"] }));
  for (let start = 1; start < 26; start += 4) {
    rows.push(...await Promise.all(Array.from({ length: Math.min(4, 26 - start) }, (_, offset) => t3.thread({ project, title: `Row ${start + offset}`, model: "multi-turn", messages: ["first"] }))));
  }
  const filler = await t3.thread({ project, title: "Filler", messages: ["first"] });
  const command = (client: any, type: string, threadId: string) => client["orchestration.dispatchCommand"]({ type, commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(threadId) });
  await rpc((client) => Effect.gen(function* () { for (const row of rows.slice(0,25)) yield* command(client, "thread.settle", row.threadId); }));
  await browser.addInitScript(() => {
    const nativeFetch = window.fetch;
    (window as any).scenarioSnapshots = [];
    window.fetch = async (...args) => {
      const response = await nativeFetch(...args);
      if (String(args[0] instanceof Request ? args[0].url : args[0]).includes("/api/orchestration/shell")) {
        const snapshot = await response.clone().json();
        if (snapshot.threads) (window as any).scenarioSnapshots.push({ sequence: snapshot.snapshotSequence, threadIds: snapshot.threads.map((t: any) => t.id), olderSettled: snapshot.olderSettled });
      }
      return response;
    };
    const Native = window.WebSocket;
    const sockets = new Set<WebSocket>();
    (window as any).scenarioOffline = false;
    (window as any).scenarioSockets = sockets;
    window.WebSocket = class extends Native {
      constructor(url: string | URL, protocols?: string | string[]) {
        const isAppSocket = new URL(String(url), location.href).pathname === "/ws";
        super(isAppSocket && (window as any).scenarioOffline ? "ws://127.0.0.1:1/ws" : url, protocols);
        if (new URL(String(url), location.href).pathname === "/ws") {
          sockets.add(this);
          this.addEventListener("open", () => { if ((window as any).scenarioOffline) this.close(); });
          this.addEventListener("close", () => sockets.delete(this));
        }
      }
    };
  });
  await t3.open(rows[0]!);
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 3000)); (window as any).scenarioOffline = true; for (const socket of (window as any).scenarioSockets) socket.close(); });
  await browser.locator("body").press("Control+k");
  await screen.getByRole("combobox").fill("Snooze");
  await screen.getByRole("option", "Snooze", { exact: true }).tap();
  await screen.getByRole("option", /Tomorrow/).tap();
  await screen.getByText("Pending", { exact: true }).waitFor();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 700)); });
  await app.screenshot("offline-snooze-pending");
  const queued = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:thread-triage-outbox") ?? "{}"));
  console.log("Queued snooze", JSON.stringify(queued));
  await rpc((client) => Effect.gen(function* () {
    yield* command(client, "thread.settle", rows[25]!.threadId);
    for (let i = 0; i < 560; i++) { yield* command(client, "thread.pin", filler.threadId); yield* command(client, "thread.unpin", filler.threadId); }
  }));
  await browser.evaluate(() => { (window as any).scenarioOffline = false; });
  // Allow the real reconnect and outbox replay, then reload to show authoritative host state.
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 15000)); });
  const projection: any = await rpc((client) => client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(rows[0]!.threadId) }));
  const snapshots = await browser.evaluate(() => (window as any).scenarioSnapshots);
  const outbox = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:thread-triage-outbox") ?? "{}"));
  const entry = queued.entries[0];
  const receipts = JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, `select command_id, command_type, status from orchestration_command_receipts where command_id = '${entry.commandId}'`], { encoding: "utf8" }) || "[]");
  const events = JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, `select command_id, event_type from orchestration_events where command_id = '${entry.commandId}' and event_type = 'thread.snoozed'`], { encoding: "utf8" }) || "[]");
  const evidence = { queued: entry, reconnectSnapshots: snapshots, outboxAfterReconnect: outbox, hostSnoozedUntil: projection.thread.snoozedUntil, receipts, events };
  console.log("Snooze delivery evidence", JSON.stringify(evidence));
  if (process.env.T3_PROOF_ARTIFACT_DIR) writeFileSync(`${process.env.T3_PROOF_ARTIFACT_DIR}/delivery-${Date.now()}.json`, JSON.stringify(evidence, null, 2));
  if (!snapshots.some((snapshot: any) => snapshot.olderSettled !== undefined && !snapshot.threadIds.includes(rows[0]!.threadId))) throw new Error("Setup did not force a snapshot omitting Row 0");
  await t3.open(rows[0]!);
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 2000)); });
  await app.screenshot("snooze-after-reconnect");
  expect(JSON.stringify({ snoozedUntil: projection.thread.snoozedUntil, receipts, events })).toBe(JSON.stringify({
    snoozedUntil: entry.action.snoozedUntil,
    receipts: [{ command_id: entry.commandId, command_type: "thread.snooze", status: "accepted" }],
    events: [{ command_id: entry.commandId, event_type: "thread.snoozed" }],
  }));
});
