import * as NodeSqlite from "node:sqlite";

import { assert, it } from "@effect/vitest";
import {
  CommandId,
  MessageId,
  EventId,
  NodeId,
  type OrchestrationV2DomainEvent,
  type OrchestrationV2ProviderTurn,
  type OrchestrationV2Run,
  type OrchestrationV2RunAttempt,
  PlanId,
  ProjectId,
  ProviderDriverKind,
  ProviderInstanceId,
  ProviderSessionId,
  ProviderThreadId,
  ProviderTurnId,
  RunAttemptId,
  RunId,
  RuntimeRequestId,
  ThreadId,
  TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Layer from "effect/Layer";
import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import * as SqlClient from "effect/sql/SqlClient";
import * as Statement from "effect/sql/Statement";
import {
  orchestrationCommandDuration,
  orchestrationCommandsTotal,
} from "../observability/Metrics.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as WorktreeSetupTracker from "../project/WorktreeSetupTracker.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import * as DelegatedTaskQuestionReactor from "./DelegatedTaskQuestionReactor.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
import * as EventSink from "./EventSink.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";

declare module "node:sqlite" {
  interface StatementSync {
    // Node 26 has this; @types/node 24 does not declare it yet.
    stat(counter: "vmStep"): number;
  }
}

const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "gpt-5.1-codex" };
const adapter = {
  instanceId,
  driver: ProviderDriverKind.make("codex"),
  getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
  planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
  openSession: () => Effect.die("No provider process needed for metadata controls"),
} as ProviderAdapter.ProviderAdapterV2["Service"];
const layerDatabase = SqlitePersistence.layerMemory;
const makeTestLayer = (
  wrapProjectionStore?: (
    store: ProjectionStore.ProjectionStoreV2Shape,
  ) => ProjectionStore.ProjectionStoreV2Shape,
) =>
  Layer.mergeAll(
    layerDatabase,
    ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest), Layer.provide(layerDatabase)),
    EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
    ProviderReplayHarness.layerWithRegistry(
      { name: "control-reads" },
      ProviderAdapterRegistry.layerFromAdapters([adapter]),
      {
        databaseLayer: layerDatabase,
        runEffectWorker: false,
        ...(wrapProjectionStore ? { wrapProjectionStore } : {}),
      },
    ),
  );
const layerTest = makeTestLayer();


const N = Number(process.env.BENCH_RUNS ?? "500");
const REPS = Number(process.env.BENCH_REPS ?? "5");
const pad = "x".repeat(2400);
const median = (xs: Array<number>) => {
  const s = [...xs].sort((a, b) => a - b);
  return s.length % 2 ? s[(s.length - 1) / 2]! : (s[s.length / 2 - 1]! + s[s.length / 2]!) / 2;
};

it.effect("bench queued commands on a long thread", () =>
  Effect.gen(function* () {
    const orchestrator = yield* Orchestrator.OrchestratorV2;
    const projections = yield* ProjectionStore.ProjectionStoreV2;
    const sql = yield* SqlClient.SqlClient;
    const threadId = ThreadId.make("thread:bench");
    const driver = ProviderDriverKind.make("codex");
    const now = yield* DateTime.now;
    yield* orchestrator.dispatch({
      type: "thread.create", commandId: CommandId.make("create-bench"), threadId,
      projectId: ProjectId.make("project:bench"), title: "Bench", modelSelection,
      runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null,
      createdBy: "user", creationSource: "web",
    });
    const providerThreadId = ProviderThreadId.make("provider-thread:bench");
    yield* projections.apply({
      id: EventId.make("event:bench:provider-thread"), type: "provider-thread.updated", threadId,
      driver, providerInstanceId: instanceId, occurredAt: now,
      payload: { id: providerThreadId, appThreadId: threadId, ownerNodeId: null, driver,
        providerInstanceId: instanceId, providerSessionId: null, nativeThreadRef: null,
        nativeConversationHeadRef: null, status: "idle", firstRunOrdinal: 1, lastRunOrdinal: 1,
        handoffIds: [], forkedFrom: null, createdAt: now, updatedAt: now, pendingBackgroundTasks: [] },
    });
    let seq = 0;
    const dispatch = (text: string) => orchestrator.dispatch({
      type: "message.dispatch", commandId: CommandId.make(`dispatch:bench:${++seq}`), threadId,
      messageId: MessageId.make(`message:bench:${seq}`), text, attachments: [],
      dispatchMode: { type: "defer_start" }, createdBy: "user", creationSource: "web",
    });
    const lastRun = Effect.gen(function* () {
      const [row] = yield* sql<{ id: string }>`SELECT run_id AS id FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} ORDER BY ordinal DESC LIMIT 1`;
      return (yield* projections.getThreadRecords(threadId, ["runs"], { runIds: [RunId.make(row!.id)] })).runs[0]!;
    });
    const t0 = performance.now();
    for (let i = 0; i < N; i++) {
      yield* dispatch(`Request ${i} ${pad}`);
      const run = yield* lastRun;
      yield* projections.apply({
        id: EventId.make(`event:bench:${i}:run`), type: "run.updated", threadId, runId: run.id, occurredAt: now,
        payload: { ...run, providerThreadId, status: "completed", queuePosition: null, startedAt: now, completedAt: now },
      });
      const nodeId = NodeId.make(`node:bench:${i}:assistant`);
      yield* projections.apply({
        id: EventId.make(`event:${nodeId}`), type: "node.updated", threadId, runId: run.id, nodeId, driver, occurredAt: now,
        payload: { id: nodeId, threadId, runId: run.id, rootNodeId: run.rootNodeId!, parentNodeId: run.rootNodeId,
          kind: "assistant_message", status: "completed", countsForRun: false, providerThreadId, providerTurnId: null,
          nativeItemRef: null, runtimeRequestId: null, checkpointScopeId: null, startedAt: now, completedAt: now },
      });
    }
    // Active run to steer into.
    yield* dispatch("/compact");
    const activeRun = yield* lastRun;
    yield* projections.apply({
      id: EventId.make("event:bench:active:run"), type: "run.updated", threadId, runId: activeRun.id, occurredAt: now,
      payload: { ...activeRun, providerThreadId, status: "running", queuePosition: null, startedAt: now, completedAt: null },
    });
    yield* projections.apply({
      id: EventId.make("event:bench:active-turn"), type: "provider-turn.updated", threadId, runId: activeRun.id, occurredAt: now,
      payload: { id: ProviderTurnId.make("provider-turn:bench"), providerThreadId, nodeId: activeRun.rootNodeId!,
        runAttemptId: activeRun.activeAttemptId!, nativeTurnRef: { driver, nativeId: "native:bench", strength: "strong" },
        ordinal: 1, status: "running", startedAt: now, completedAt: null },
    });
    const seedMs = performance.now() - t0;
    const [counts] = yield* sql<{ runs: number; msgs: number; items: number; nodes: number }>`SELECT
      (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId}) AS runs,
      (SELECT COUNT(*) FROM orchestration_v2_projection_messages WHERE thread_id = ${threadId}) AS msgs,
      (SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}) AS items,
      (SELECT COUNT(*) FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId}) AS nodes`;
    const timed = <A, E, R>(e: Effect.Effect<A, E, R>) => Effect.gen(function* () {
      const s = performance.now(); yield* e; return performance.now() - s;
    });
    const results: Record<string, Array<number>> = { "message.dispatch (queued)": [], "queued-run.edit": [],
      "queued-run.reorder": [], "queued-run.cancel": [], "queued-message.promote-to-steer": [] };
    for (let r = 0; r < REPS; r++) {
      results["message.dispatch (queued)"]!.push(yield* timed(dispatch(`Queued A ${r}`)));
      const a = yield* lastRun;
      yield* dispatch(`Queued B ${r}`);
      const b = yield* lastRun;
      results["queued-run.edit"]!.push(yield* timed(orchestrator.dispatch({ type: "queued-run.edit",
        commandId: CommandId.make(`edit:${r}`), threadId, runId: a.id, text: `Edited ${r}` })));
      results["queued-run.reorder"]!.push(yield* timed(orchestrator.dispatch({ type: "queued-run.reorder",
        commandId: CommandId.make(`reorder:${r}`), threadId, runId: b.id, beforeRunId: a.id })));
      results["queued-run.cancel"]!.push(yield* timed(orchestrator.dispatch({ type: "queued-run.cancel",
        commandId: CommandId.make(`cancel:${r}`), threadId, runId: b.id })));
      results["queued-message.promote-to-steer"]!.push(yield* timed(orchestrator.dispatch({
        type: "queued-message.promote-to-steer", commandId: CommandId.make(`promote:${r}`), threadId,
        queuedRunId: a.id, targetRunId: activeRun.id })));
    }
    const out = { N, REPS, seedMs: Math.round(seedMs), counts,
      ms: Object.fromEntries(Object.entries(results).map(([k, v]) => [k, {
        median: +median(v).toFixed(1), min: +Math.min(...v).toFixed(1), max: +Math.max(...v).toFixed(1),
        runs: v.map((x) => +x.toFixed(1)) }])) };
    (yield* Effect.promise(() => import("node:fs/promises"))).appendFile(process.env.BENCH_OUT ?? "/tmp/factory-issue-47538-triage/bench/out.jsonl", JSON.stringify(out) + "\n");
    assert.ok(true);
  }).pipe(Effect.provide(layerTest)),
);
