import { expect } from "e2e";
import { spawn, execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { prepareHome, SCENARIO_MACHINE_ENV } from "./start-app.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const home = `${T3_HOME}-restart-proof`;
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const sql = (query: string) => JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${home}/userdata/statev2.sqlite`, query], { encoding: "utf8" }) || "[]");
const snapshot = () => ({ task: sql("SELECT title,last_run_status,last_run_at,next_run_at,run_count,thread_id,last_run_error FROM scheduled_tasks")[0], receipts: sql("SELECT count(*) AS count FROM (SELECT command_id FROM orchestration_command_receipts WHERE command_id LIKE 'scheduled-task:%:scheduled' AND status='accepted' UNION SELECT command_id FROM orchestration_v2_command_receipts WHERE command_id LIKE 'scheduled-task:%:scheduled' AND status='accepted')")[0].count, messages: sql("SELECT count(*) AS count FROM orchestration_v2_projection_messages WHERE role='user' AND json_extract(payload_json,'$.text')='Say hello from the fixed-time slot'")[0].count });

async function launch(port: number, devUrl: string) {
  const ready = Promise.withResolvers<{ host: string; token: string; inspector: string }>();
  let token = "", inspector = "";
  const child = spawn(process.execPath, ["--inspect=127.0.0.1:0", "apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", home, "--dev-url", devUrl], {
    cwd: APP_DIR,
    env: { ...process.env, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", TZ: "UTC", ...SCENARIO_MACHINE_ENV },
    stdio: ["ignore", "pipe", "pipe"],
  });
  const consume = (data: Buffer) => {
    const text = data.toString();
    token = /Token:\s*(\S+)/.exec(text)?.[1] ?? token;
    inspector = /Debugger listening on (ws:\/\/\S+)/.exec(text)?.[1] ?? inspector;
    if (token && inspector) ready.resolve({ host: `http://127.0.0.1:${port}`, token, inspector });
  };
  child.stdout.on("data", consume); child.stderr.on("data", consume);
  child.once("exit", code => ready.reject(new Error(`Proof server exited: ${code}`)));
  return { child, ready: await ready.promise };
}
async function debuggerClient(url: string) {
  const ws = new WebSocket(url);
  await new Promise<void>((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = reject; });
  let sequence = 0;
  const pending = new Map<number, { resolve: (x: any) => void; reject: (x: any) => void }>();
  const paused = Promise.withResolvers<any>();
  ws.onmessage = event => {
    const message = JSON.parse(String(event.data));
    if (message.method === "Debugger.paused") paused.resolve(message.params);
    if (message.id) { const p = pending.get(message.id); pending.delete(message.id); message.error ? p?.reject(message.error) : p?.resolve(message.result); }
  };
  const call = (method: string, params = {}) => new Promise<any>((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
  await call("Debugger.enable");
  return { call, paused: paused.promise, close: () => ws.close() };
}

test("An interrupted fixed-time slot is delivered once after restart within grace", WEB, async ({ t3, app, screen }) => {
  await t3.project("Local notes");
  await runPromise(prepareHome(home));
  // A per-run free TCP port; no shared server or data is touched.
  const net = await import("node:net");
  const reservation = net.createServer(); await new Promise<void>(r => reservation.listen(0, "127.0.0.1", r));
  const port = (reservation.address() as net.AddressInfo).port; await new Promise<void>(r => reservation.close(() => r()));
  let server = await launch(port, app.baseUrl ?? "");
  let debug: Awaited<ReturnType<typeof debuggerClient>> | undefined;
  try {
    const state = makeState(home);
    await state.state.project("Sample");
    const projectId = sql("SELECT project_id FROM projection_projects WHERE title='Sample'")[0].project_id;
    const rpc = <A>(f: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.scoped(Effect.flatMap(rpcClient(home, server.ready.host), f)) as any);
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog", "Add Environment", { exact: true });
    await dialog.getByPlaceholder("backend.example.com").fill(server.ready.host);
    await dialog.getByPlaceholder("PAIRCODE").fill(server.ready.token);
    await dialog.getByRole("button", "Add environment").tap();
    await dialog.waitFor({ state: "hidden" });
    debug = await debuggerClient(server.ready.inspector);
    const source = readFileSync(`${APP_DIR}/apps/server/src/scheduledTasks/ScheduledTaskService.ts`, "utf8");
    const lineNumber = source.slice(0, source.indexOf("        const fireKey =")).split("\n").length - 1;
    console.log("Breakpoint after markRunning:", await debug.call("Debugger.setBreakpointByUrl", { urlRegex: "ScheduledTaskService\\.ts$", lineNumber }));
    const slot = new Date(Math.ceil((Date.now() + 20_000) / 60_000) * 60_000);
    const timeOfDay = slot.toISOString().slice(11, 16);
    await rpc(client => client["scheduledTasks.upsert"]({ title: "Daily repro task", prompt: "Say hello from the fixed-time slot", enabled: true, schedule: { type: "fixed_time", timeOfDay }, projectId, threadMode: "new_thread", workspaceStrategy: { type: "root" }, modelSelection: { instanceId: "devReplay", model: "multi-turn" }, runtimeMode: "full-access", interactionMode: "default" }));
    await app.open("/settings/scheduled-tasks");
    await screen.getByRole("dialog", "Settings", { exact: true }).getByText("Daily repro task", { exact: true }).waitFor();
    await app.screenshot("before-interruption");
    await debug.paused;
    console.log("PRE-DISPATCH CRASH", JSON.stringify(snapshot()));
    server.child.kill("SIGKILL"); debug.close(); debug = undefined;
    await new Promise<void>(r => server.child.once("exit", () => r()));
    await delay(2000);
    server = await launch(port, app.baseUrl ?? "");
    // Observe multiple real scheduler polls on both sides, within the ten-minute grace.
    await delay(20_000);
    await app.open("/settings/scheduled-tasks");
    await screen.getByRole("dialog", "Settings", { exact: true }).getByText("Daily repro task", { exact: true }).waitFor();
    const result = snapshot();
    console.log("AFTER RESTART", JSON.stringify(result));
    await app.screenshot("recovered-fixed-time-slot");
    expect(result.task.last_run_status).toBe("succeeded");
    expect(result.task.run_count).toBe(1);
    expect(result.receipts).toBe(1);
    expect(result.messages).toBe(1);
    const delivered = sql("SELECT thread_id FROM orchestration_v2_projection_messages WHERE role='user' AND json_extract(payload_json,'$.text')='Say hello from the fixed-time slot'")[0];
    const environment = await (await fetch(`${server.ready.host}/.well-known/t3/environment`)).json();
    await app.open(`/${environment.environmentId}/${delivered.thread_id}`);
    await screen.getByRole("button", "Automation Daily repro task", { exact: true }).tap();
    await screen.getByText("Say hello from the fixed-time slot", { exact: true }).waitFor();
    await app.screenshot("delivered-slot-prompt");
  } finally {
    debug?.close();
    server.child.kill("SIGTERM");
    await new Promise<void>(r => server.child.once("exit", () => r()));
  }
});
