import { execFileSync } from "node:child_process";
import { DatabaseSync } from "node:sqlite";
import { mkdirSync, writeFileSync, appendFileSync, existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeWS from "@effect/platform-node/NodeWS";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";
import { WsRpcGroup, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";

// Run from a checkout root: node apps/server/scripts/zz-stop-proof.ts <home> <origin> <output-dir> [history=5000] [samples=36] [mode=all|seed|measure] [fixture=long|small]
// The only database connection in this driver is read-only. All seeded state comes from public app RPCs and the repository's replay provider.
const [home, origin, out, historyArg = "5000", samplesArg = "36", mode = "all", fixture = "long"] =
  process.argv.slice(2);
const history = Number(historyArg),
  samples = Number(samplesArg);
mkdirSync(out, { recursive: true });
const log = (value) => {
  const line = JSON.stringify(value);
  console.log(line);
  appendFileSync(join(out, "measurements.jsonl"), line + "\n");
};
const sha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
const token = execFileSync(
  process.execPath,
  ["apps/server/src/bin.ts", "auth", "session", "issue", "--token-only", "--base-dir", home],
  { encoding: "utf8" },
).trim();
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
const ticketRes = await fetch(origin + "/api/auth/websocket-ticket", { method: "POST", headers });
if (!ticketRes.ok) throw Error("ticket " + ticketRes.status);
const { ticket } = await ticketRes.json();
const db = new DatabaseSync(join(home, "userdata", "statev2.sqlite"), { readOnly: true });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function until(fn, label, timeout = 120000) {
  const start = performance.now();
  for (;;) {
    const v = fn();
    if (v) return v;
    if (performance.now() - start > timeout) throw Error("Timeout: " + label);
    await sleep(10);
  }
}
const program = Effect.gen(function* () {
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  const rpc = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
  yield* Effect.tryPromise(async () => {
    const call = (name, input) => Effect.runPromise(rpc[name](input));
    const dispatch = (command) =>
      call("orchestration.dispatchCommand", { commandId: crypto.randomUUID(), ...command });
    const manifest = join(
      home,
      fixture === "long" ? "evidence-thread.json" : `evidence-thread-${fixture}.json`,
    );
    const existing = existsSync(manifest) ? JSON.parse(readFileSync(manifest, "utf8")) : null;
    const projectId = existing?.projectId ?? crypto.randomUUID(),
      threadId = existing?.threadId ?? crypto.randomUUID();
    if (!existing) {
      const workspace = join(
        home,
        fixture === "long" ? "synthetic-workspace" : `synthetic-workspace-${fixture}`,
      );
      mkdirSync(workspace, { recursive: true });
      execFileSync("git", ["init", "--quiet", workspace]);
      writeFileSync(join(workspace, "README.md"), "Synthetic stop performance evidence\n");
      execFileSync("git", ["-C", workspace, "add", "."]);
      execFileSync("git", [
        "-C",
        workspace,
        "-c",
        "user.name=Evidence",
        "-c",
        "user.email=evidence@example.invalid",
        "commit",
        "--quiet",
        "-m",
        "Synthetic fixture",
      ]);
      const pr = await fetch(origin + "/api/projects/mutate", {
        method: "POST",
        headers,
        body: JSON.stringify({
          type: "project.create",
          commandId: crypto.randomUUID(),
          projectId,
          title: "Stop history evidence",
          workspaceRoot: workspace,
        }),
      });
      if (!pr.ok) throw Error("project " + pr.status + " " + (await pr.text()));
      await dispatch({
        type: "thread.create",
        threadId,
        projectId,
        title: "Synthetic completed history",
        modelSelection: { instanceId: "devReplay", model: "multi-turn" },
        runtimeMode: "full-access",
        interactionMode: "default",
        branch: null,
        worktreePath: null,
        createdBy: "user",
        creationSource: "web",
      });
      writeFileSync(manifest, JSON.stringify({ projectId, threadId }));
    }
    const runByMessage = db.prepare(
      "SELECT run_id,status,payload_json FROM orchestration_v2_projection_runs WHERE thread_id=? AND json_extract(payload_json,'$.userMessageId')=?",
    );
    const runById = db.prepare(
      "SELECT status FROM orchestration_v2_projection_runs WHERE run_id=?",
    );
    const turns = db.prepare(
      "SELECT provider_turn_id FROM orchestration_v2_projection_provider_turns WHERE thread_id=? AND run_attempt_id=? AND status='running'",
    );
    const interrupts = db.prepare(
      "SELECT count(*) n FROM orchestration_v2_projection_turn_items WHERE thread_id=? AND run_id=? AND type='run_interrupt_request'",
    );
    async function send(text) {
      const messageId = crypto.randomUUID();
      await dispatch({
        type: "message.dispatch",
        threadId,
        messageId,
        text,
        attachments: [],
        dispatchMode: { type: "start_immediately" },
        createdBy: "user",
        creationSource: "web",
      });
      return await until(() => runByMessage.get(threadId, messageId), "run created");
    }
    async function settle(run) {
      return until(() => {
        const r = runById.get(run.run_id);
        return r && ["completed", "interrupted", "failed", "cancelled"].includes(r.status) && r;
      }, "settled run");
    }
    log({
      kind: "environment",
      sha,
      platform: process.platform,
      arch: process.arch,
      node: process.version,
      storage: "file-backed SQLite",
      transport: "authenticated WebSocket RPC",
      provider: "repository Replay (dev)",
      history,
      samplesPerAction: samples,
      timed: "RPC request to acknowledgement; provider shutdown awaited outside sample",
    });
    const seedStart = performance.now();
    const completed = () =>
      db
        .prepare(
          "SELECT count(*) n FROM orchestration_v2_projection_runs WHERE thread_id=? AND status='completed'",
        )
        .get(threadId).n;
    if (mode !== "measure") {
      await dispatch({
        type: "thread.model-selection.set",
        threadId,
        modelSelection: { instanceId: "devReplay", model: "multi-turn" },
      });
      for (let i = completed(); i < history; i++) {
        const run = await send("Reply briefly.");
        const status = await settle(run);
        if (status.status !== "completed") throw Error("Seed run " + i + " " + status.status);
        if ((i + 1) % 100 === 0 || i === history - 1)
          log({
            kind: "seed-progress",
            completed: i + 1,
            elapsedSeconds: +((performance.now() - seedStart) / 1000).toFixed(2),
          });
      }
    }
    if (completed() !== history) throw Error("Completed history mismatch " + completed());
    if (mode === "seed") {
      log({ kind: "seed-done", completed: completed() });
      return;
    }
    await dispatch({
      type: "thread.model-selection.set",
      threadId,
      modelSelection: { instanceId: "devReplay", model: "bench-stream" },
    });
    const results = [];
    for (let i = -4; i < samples; i++)
      for (const action of ["thread.stop", "run.interrupt"]) {
        const run = await send("Stream a long response.");
        await until(
          () => turns.get(threadId, JSON.parse(run.payload_json).activeAttemptId),
          "live provider turn",
        );
        const start = performance.now();
        await dispatch({
          type: action,
          threadId,
          ...(action === "run.interrupt" ? { runId: run.run_id, holdQueue: true } : {}),
        });
        const ms = performance.now() - start;
        const recorded = interrupts.get(threadId, run.run_id).n;
        if (recorded < 1) throw Error("Missing run_interrupt_request");
        const terminal = await settle(run);
        if (terminal.status !== "interrupted")
          throw Error("Stop terminal status " + terminal.status);
        await until(
          () => !turns.get(threadId, JSON.parse(run.payload_json).activeAttemptId),
          "provider turn ended",
        );
        const row = {
          kind: i < 0 ? "warmup" : "sample",
          index: i,
          action,
          ms: +ms.toFixed(3),
          interruptRecorded: true,
          terminalStatus: terminal.status,
        };
        log(row);
        if (i >= 0) results.push(row);
      }
    const summarize = (rows) => {
      const sorted = rows.map((r) => r.ms).sort((a, b) => a - b);
      return {
        n: sorted.length,
        median:
          (sorted[Math.floor((sorted.length - 1) / 2)] +
            sorted[Math.ceil((sorted.length - 1) / 2)]) /
          2,
        min: sorted[0],
        max: sorted.at(-1),
        p10: sorted[Math.floor(sorted.length * 0.1)],
        p90: sorted[Math.floor(sorted.length * 0.9)],
      };
    };
    const summary = {
      sha,
      history,
      storage: "file-backed SQLite",
      actions: Object.fromEntries(
        ["thread.stop", "run.interrupt"].map((action) => [
          action,
          summarize(results.filter((r) => r.action === action)),
        ]),
      ),
      allInterruptsRecorded: true,
      allStoppedRunsInterrupted: true,
      completedSeedRuns: db
        .prepare(
          "SELECT count(*) n FROM orchestration_v2_projection_runs WHERE thread_id=? AND status='completed'",
        )
        .get(threadId).n,
    };
    writeFileSync(join(out, "summary.json"), JSON.stringify(summary, null, 2) + "\n");
    log({ kind: "summary", ...summary });
  });
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
try {
  await Effect.runPromise(program);
} finally {
  db.close();
}
