/**
 * WP-08 active cutover E2E (InMemory Host) — dual delivery adversarial + smoke.
 *
 * Uses mode=active ONLY with explicit test Gate B token.
 * Does not touch production TaskDispatcher / 18766.
 */

import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
  AgentHostRegistry,
  DualDeliveryGuard,
  FactToDoorbellBridge,
  HostSwitchboard,
  InMemoryHostAdapter,
  SwitchboardModeError,
  SwitchboardPaths,
  WorkerBindingStore,
  type ActiveAuthorization,
} from "../index.ts";
import type { WorkerBindingRevision } from "../contracts/WorkerBinding.ts";

async function tempPaths(): Promise<SwitchboardPaths> {
  const root = await mkdtemp(join(tmpdir(), "sb-wp08-e2e-"));
  const persistDir = join(root, ".codeflowmu", "state");
  await mkdir(persistDir, { recursive: true });
  return new SwitchboardPaths({ persistDir });
}

const gateB: ActiveAuthorization = {
  approved: true,
  decisionRef: "TEST-approve_active-wp08-e2e",
  approvedAt: new Date().toISOString(),
  approvedBy: "ADMIN-TEST",
};

async function seedBinding(
  paths: SwitchboardPaths,
  workerId: string,
  hostId: string,
): Promise<void> {
  const store = new WorkerBindingStore(paths);
  const rev: WorkerBindingRevision = {
    schema: "codeflowmu.worker-binding/v1",
    bindingId: `bind-${workerId}`,
    revision: 1,
    workerId,
    host: {
      hostId,
      externalSessionId: `mem-session-${workerId}`,
      mode: "local",
    },
    state: "ready",
    createdAt: new Date().toISOString(),
    createdBy: "wp08-e2e",
  };
  await store.append(rev);
}

describe("WP-08 active-cutover e2e (InMemory)", () => {
  it("single role smoke: admit → doorbell → wake → completed; no dual delivery", async () => {
    const paths = await tempPaths();
    const host = new InMemoryHostAdapter({ hostId: "host-mem" });
    const registry = new AgentHostRegistry();
    registry.register(host);
    await seedBinding(paths, "DEV-01", "host-mem");

    const guard = new DualDeliveryGuard({
      mode: "active",
      activeAuthorization: gateB,
    });
    const bridge = new FactToDoorbellBridge({ paths, mode: "active" });
    const board = new HostSwitchboard({
      paths,
      registry,
      mode: "active",
      activeAuthorization: gateB,
      dualDeliveryGuard: guard,
    });

    const enq = await bridge.enqueueFromAdmittedWork({
      workerId: "DEV-01",
      summary: "WP-08 smoke",
      dedupeKey: "dk-e2e-1",
      sourceFactRefs: ["TASK-20260805-009"],
      admission: { decision: "allow", reason: "allowed" },
      taskId: "TASK-20260805-009",
      priority: "P0",
    });
    assert.equal(enq.status, "enqueued");

    // Legacy path must be blocked under active.
    assert.throws(
      () => guard.assertLegacySendAllowed(`${enq.doorbellId}`),
      SwitchboardModeError,
    );

    const wake = await board.wakeWorker({
      workerId: "DEV-01",
      doorbellId: enq.doorbellId!,
    });
    assert.equal(wake.status, "completed");
    if (wake.status !== "completed") return;
    assert.equal(wake.invokedHostStartRun, true);
    assert.ok(wake.deliveryAttemptId.startsWith("attempt-"));

    // Same doorbell cannot be woken twice (no longer pending).
    const again = await board.wakeWorker({
      workerId: "DEV-01",
      doorbellId: enq.doorbellId!,
    });
    assert.equal(again.status, "blocked");

    // Duplicate doorbell for same work key.
    const dup = await bridge.enqueueFromAdmittedWork({
      workerId: "DEV-01",
      summary: "WP-08 smoke",
      dedupeKey: "dk-e2e-1",
      sourceFactRefs: ["TASK-20260805-009"],
      admission: { decision: "allow", reason: "allowed" },
    });
    assert.equal(dup.status, "duplicate");

    assert.equal(guard.isDualDelivery(String(enq.doorbellId)), false);

    const settled = await board.mailbox.list("DEV-01", "settled");
    assert.equal(settled.length, 1);
  });

  it("dual-delivery adversarial: emergency stop on detection", async () => {
    const guard = new DualDeliveryGuard({
      mode: "active",
      activeAuthorization: gateB,
    });
    // Simulate buggy wiring that also called legacy.
    guard.recordAttempt("work-x", "switchboard");
    try {
      guard.assertLegacySendAllowed("work-x");
    } catch {
      /* expected block — but if a bug recorded anyway: */
    }
    guard.recordAttempt("work-x", "legacy");
    assert.equal(guard.isDualDelivery("work-x"), true);
    guard.emergencyStop("dual_delivery_detected");
    assert.equal(guard.mode, "off");
    assert.throws(() => guard.assertSwitchboardSendAllowed("work-x"));
  });

  it("active → off rollback restores legacy-send permission", () => {
    const guard = new DualDeliveryGuard({
      mode: "active",
      activeAuthorization: gateB,
    });
    assert.throws(() => guard.assertLegacySendAllowed());
    guard.setMode("off");
    guard.assertLegacySendAllowed("legacy-ok");
    assert.deepEqual(guard.attemptsFor("legacy-ok"), ["legacy"]);
  });
});
