/**
 * # blotter/claims — the latency-claim gate (ADR-0040 / kestrel-w7la.3, clock-honest wakes §5)
 *
 * The hook surface the platform's FORBIDDEN-CLAIMS lint (platform ev3) calls: the `clock_honest`
 * rankability leg rides the session record, and a latency claim may cite ONLY a session whose leg is
 * `pass`. A latency-blind session is *valid* — certified, gradable, comparable in exploratory grids —
 * but "can never ground a latency claim" (CONTEXT.md, Clock-honest wake). The OSS obligation ends at
 * carrying the leg honestly and refusing here; the claim lint itself is platform-side.
 *
 * LEG-scoped, not conjunction-scoped (§5): the gate reads `blotter.rankability.legs.clock_honest`
 * alone — a clock-honest session that is not leaderboard-rankable for OTHER reasons (e.g. pre-cutoff)
 * still grounds a latency claim; rankability is a different axis.
 */

import type { RankableReason } from "../bus/types.ts";
import type { Blotter } from "./types.ts";

/** The gate's verdict: allowed, or a NAMED fail-closed refusal (never a silent pass). */
export type LatencyClaimVerdict =
  | { readonly allowed: true }
  | { readonly allowed: false; readonly reason: RankableReason };

/**
 * Refuse any latency claim citing a session whose `clock_honest` leg is not `pass` (clock-honest
 * wakes §5). FAIL-CLOSED: a strict `"pass"` on the projected leg is the ONLY allowed state — a hard
 * `"fail"` (platform-side revocation, `meta.clock_honest: false`) refuses as `not-clock-honest`, and
 * EVERYTHING else (leg `"unknown"`, a missing/malformed rankability record) refuses as
 * `clock-honest-unknown`. Never a silent pass on an unattested session.
 */
export function latencyClaimGate(blotter: Blotter): LatencyClaimVerdict {
  // Defensive read: the gate is a claim boundary, so a malformed record refuses instead of throwing.
  const leg: unknown = (blotter as { rankability?: { legs?: { clock_honest?: unknown } } }).rankability?.legs
    ?.clock_honest;
  if (leg === "pass") return { allowed: true };
  if (leg === "fail") {
    return {
      allowed: false,
      reason: {
        kind: "not-clock-honest",
        detail:
          "latency claim refused: the session's clock-honest attestation is REVOKED " +
          "(rankability.legs.clock_honest=fail, a platform-side revocation) — its latency accounting is marked " +
          "defective (ADR-0040, kestrel-w7la.3)",
      },
    };
  }
  return {
    allowed: false,
    reason: {
      kind: "clock-honest-unknown",
      detail:
        "latency claim refused: the session is latency-blind or its clock-honest leg is unknown/missing " +
        "(rankability.legs.clock_honest is not 'pass') — a latency-blind session can never ground a latency " +
        "claim (fail-closed, ADR-0040, kestrel-w7la.3)",
    },
  };
}
