# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-behavioral-fingerprint-after-a-hardware-key-rotation-and-why-the-naive-answer-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-behavioral-fingerprint-after-a-hardware-key-rotation-and-why-the-naive-answer-fails.warrant.json
# Markdown SHA-256:   22fea4704f7c97ff1bc7ed12b48186ec0180d6a2f8404c1558e535acbf49a9a9
# Code AST SHA-256:   f86a188bd6abb80b1f27cba6022c8a86009899ad49da3d6f95d151d38b3cf2cd
# Verified Classes:   StaleFingerprintAuthorizationError, Sample, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleFingerprintAuthorizationError(RuntimeError):
    """Raised when a behavioral fingerprint score is used to authorize a
    decision while its rolling window contains samples not attributable to
    the currently-presented attestation key, or before warm-up completes."""
    pass


@dataclass(frozen=True)
class Sample:
    key_id: str
    timestamp: float
    score: float


@dataclass(frozen=True)
class Attestation:
    key_id: str
    minted_at: float
    witnessed_by_prior_key: bool


W_MIN = 20                 # minimum samples under current key
SAMPLE_INTERVAL = 30.0     # seconds between samples
WINDOW_SECONDS = 600.0     # rolling window length
SCORE_THRESHOLD = 0.85


def authorize_privileged_tool(
    now: float,
    attestation: Attestation,
    window: list[Sample],
) -> bool:
    # 1. Cryptographic validity of the presented key.
    if not attestation.witnessed_by_prior_key:
        # An unwitnessed rotation cannot be trusted to be a legitimate
        # succession; refuse to grant privileges regardless of fingerprint.
        raise StaleFingerprintAuthorizationError(
            f"key {attestation.key_id} was not witnessed by a prior key; "
            "rotation lineage unproven"
        )

    # 2. Partition the window: only samples under the current key count.
    current = [
        s for s in window
        if s.key_id == attestation.key_id
        and (now - s.timestamp) <= WINDOW_SECONDS
    ]

    # 3. Warm-up check: if the current key has not existed long enough to
    #    fill the minimum sample count, the instance is behaviorally unproven.
    elapsed_since_mint = now - attestation.minted_at
    required_elapsed = W_MIN * SAMPLE_INTERVAL
    if len(current) < W_MIN or elapsed_since_mint < required_elapsed:
        # WARMING state: cryptographically valid, behaviorally unproven.
        # Deny privileged tools; caller should fall back to restricted set.
        raise StaleFingerprintAuthorizationError(
            f"key {attestation.key_id} in WARMING: "
            f"{len(current)}/{W_MIN} samples, "
            f"{elapsed_since_mint:.0f}/{required_elapsed:.0f}s elapsed; "
            "fingerprint not yet attributable"
        )

    # 4. Only now is the score meaningful for this key holder.
    avg = sum(s.score for s in current) / len(current)
    return avg > SCORE_THRESHOLD
