# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-attestation-liveness-decay-when-a-hardware-rooted-identity-key-stays-valid-but-the-behavioral-fingerprint-it-was-bound-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-attestation-liveness-decay-when-a-hardware-rooted-identity-key-stays-valid-but-the-behavioral-fingerprint-it-was-bound-t.warrant.json
# Markdown SHA-256:   0fdd6fdb4679b0f7e7a4c6b289c5b54928dd459292e427b3cc6830f7c87c83f6
# Code AST SHA-256:   a8c8d4eca652deb075f945e41cc4b3fc0f88cc7fbdc4fd12d2ce66793f80b6f5
# Verified Classes:   AttestationLivenessError, AttestationState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import List, Optional


class AttestationLivenessError(RuntimeError):
    """Raised when a hardware-rooted identity's behavioral binding has decayed
    past its drift budget and cannot be renewed by fresh attestation."""
    pass


@dataclass
class AttestationState:
    ak_id: str
    epoch: int
    reference_fp: List[float]          # current epoch centroid
    enrolled_fp: List[float]           # immutable T0 anchor
    tau: float = 0.18                  # point-anchor distance threshold
    delta: float = 0.04                # per-step continuity bound
    drift_budget: float = 0.60         # cumulative drift allowance per epoch
    monotonic_window: int = 40         # max consecutive steps toward boundary
    cumulative_drift: float = 0.0
    toward_boundary_run: int = 0
    history: List[List[float]] = field(default_factory=list)


def _cosine_distance(a: List[float], b: List[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0.0 or nb == 0.0:
        return 1.0
    return 1.0 - dot / (na * nb)


def admit_action(
    state: AttestationState,
    fp_t: List[float],
    fresh_quote_valid: bool,
    quote_fp: Optional[List[float]] = None,
) -> str:
    """Returns 'admit', 'renew_required', or raises AttestationLivenessError."""
    step = _cosine_distance(fp_t, state.history[-1]) if state.history else 0.0
    anchor = _cosine_distance(fp_t, state.enrolled_fp)
    prev_anchor = (
        _cosine_distance(state.history[-1], state.enrolled_fp)
        if state.history else anchor
    )

    if step > state.delta:
        raise AttestationLivenessError(
            f"per-step discontinuity {step:.3f} > delta {state.delta} "
            f"for AK {state.ak_id} epoch {state.epoch}"
        )

    state.cumulative_drift += step
    state.toward_boundary_run = (
        state.toward_boundary_run + 1 if anchor > prev_anchor else 0
    )

    budget_exhausted = state.cumulative_drift >= state.drift_budget
    boundary_walk = state.toward_boundary_run > state.monotonic_window
    point_ok = anchor < state.tau

    if not point_ok:
        raise AttestationLivenessError(
            f"point-anchor distance {anchor:.3f} >= tau {state.tau} "
            f"for AK {state.ak_id} epoch {state.epoch}"
        )

    if budget_exhausted or boundary_walk:
        if not fresh_quote_valid:
            raise AttestationLivenessError(
                f"drift budget exhausted (cum={state.cumulative_drift:.3f}, "
                f"walk={state.toward_boundary_run}) and no fresh quote for "
                f"AK {state.ak_id} epoch {state.epoch}; quarantine"
            )
        if quote_fp is None or _cosine_distance(quote_fp, fp_t) > 1e-6:
            raise AttestationLivenessError(
                f"fresh quote fingerprint does not match current fingerprint "
                f"for AK {state.ak_id} epoch {state.epoch}; quarantine"
            )
        # Renew: advance epoch, re-anchor to current fingerprint, reset budget.
        state.epoch += 1
        state.reference_fp = fp_t
        state.cumulative_drift = 0.0
        state.toward_boundary_run = 0
        state.history.append(fp_t)
        return "renew_required"

    state.history.append(fp_t)
    return "admit"
