/**
 * Replay-frame sealer (recoverable K_content) — PLAN_RELAY_AGENT T19 (FIX 3).
 *
 * Live host→client frames use the EPHEMERAL DirectionalKeys.h2c (forward-secret, gone after
 * reconnect). But "refresh the page and the Claude session is still there" needs the ring-buffer /
 * preview ciphertext to be RECOVERABLE — so every replay-bound output is ALSO sealed under the
 * host-scoped recoverable K_content = deriveContentKey({ hostContentSecret, sessionId, alg }),
 * DISTINCT from the live h2c frame. The browser re-derives the identical K_content (P5) and opens
 * it (P6). This is the single agent-side consumer of the FIX 3 recoverable key.
 *
 * INTEGRATION SEAM: the frozen §4.4 replay-crypto IMPLEMENTATIONS live in P4 `relay-e2e/`
 * (`deriveContentKey`, `sealReplayFrame`). P4 is not built yet, so they are INJECTED here typed to
 * the frozen relay-contracts signatures — production wiring passes the relay-e2e impls verbatim.
 * `hostContentSecret` comes from Keystore.loadContentSecret() (T3); NEVER the ephemeral key,
 * NEVER logged, NEVER sent to the relay (INV2/INV9).
 *
 * PER-GENERATION EPOCH (F6 fix): K_content = HKDF(hostContentSecret, salt=sessionId, info=const) is
 * byte-identical for a given (host, sessionId) and RECOVERABLE by design — but the deterministic seal
 * nonce is seq, which resets to 0 on every sealer reconstruction (restart / re-attach). Two sealer
 * GENERATIONS would therefore seal DISTINCT plaintext under the SAME (key, nonce) → catastrophic AEAD
 * reuse. Each `createReplaySealer` call mints a FRESH, NON-SECRET `epoch` (randomUUID) that is folded
 * into K_content derivation, so a restart / new generation yields a FRESH key even for the same
 * (hostContentSecret, sessionId); seq=0 can never collide across generations. The epoch is exposed on
 * the sealer so the wiring can persist it with the ring buffer / replay stream and serve it to the
 * browser, which re-derives the matching key. Recoverability WITHIN one generation (same epoch ⇒ same
 * key) is preserved.
 */
import { randomUUID } from 'node:crypto'
import type { AeadAlg, AeadKey, E2EEnvelope, ReplayKeyParams } from 'relay-contracts'

/** The two §4.4 replay primitives, typed to the frozen relay-contracts signatures (P4 impls). */
export interface ReplayCrypto {
  deriveContentKey(params: ReplayKeyParams): AeadKey
  sealReplayFrame(key: AeadKey, seq: bigint, plaintext: Uint8Array): E2EEnvelope
}

export interface ReplaySealer {
  /**
   * The fresh, NON-SECRET per-generation epoch folded into K_content (F6). The wiring persists it
   * with the ring buffer / replay stream so the browser re-derives the matching key.
   */
  readonly epoch: string
  /** K_content seal with monotonic seq per session (INV13); NOT the live h2c frame. */
  seal(plaintext: Uint8Array): E2EEnvelope
}

/**
 * Build a per-(host, session) replay sealer for ONE generation. A FRESH `epoch` is minted per call
 * and folded into K_content, which is derived ONCE from { hostContentSecret, sessionId, alg, epoch };
 * seq is strictly monotonic from 0 (INV13). A restart / re-attach constructs a NEW generation with a
 * NEW epoch ⇒ a FRESH key, so seq=0 never collides across generations (F6).
 */
export function createReplaySealer(
  hostContentSecret: Uint8Array,
  sessionId: string,
  alg: AeadAlg,
  crypto: ReplayCrypto,
): ReplaySealer {
  const epoch = randomUUID()
  const key = crypto.deriveContentKey({ hostContentSecret, sessionId, alg, epoch })
  let seq = 0n
  return {
    epoch,
    seal(plaintext: Uint8Array): E2EEnvelope {
      const env = crypto.sealReplayFrame(key, seq, plaintext)
      seq += 1n
      return env
    },
  }
}
