# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-delegated-authority-when-an-aaif-attestation-chain-is-re-anchored-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-delegated-authority-when-an-aaif-attestation-chain-is-re-anchored-mid-handoff.warrant.json
# Markdown SHA-256:   d8c18f5635b230fadedf1e756f6839901392ea793d4923b6f6b4f28be1363d0f
# Code AST SHA-256:   2f5699edfe607cdc69e1a8cb55dbb45780b951e6035110bc7f1e653ad8b6cc53
# Verified Classes:   AnchorDisposition, AnchorDiscontinuityError, TrustStoreDesyncError, Anchor, DelegatedToken, VerificationResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class AnchorDisposition(Enum):
    ACTIVE = "active"
    GRACE = "grace"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


class AnchorDiscontinuityError(RuntimeError):
    """Raised when a delegated token's anchor is not in a state that permits acceptance."""


class TrustStoreDesyncError(RuntimeError):
    """Raised when the token names an anchor the verifier has never seen — an ops fault, not an auth failure."""


@dataclass
class Anchor:
    anchor_id: str
    disposition: AnchorDisposition
    grace_until: Optional[float] = None


@dataclass
class DelegatedToken:
    iss_key: str
    sub_key: str
    capability: str
    anchor_id: str          # the anchor the chain was signed under, pinned at mint time
    exp: float
    delegation_chain: List[str] = field(default_factory=list)


@dataclass
class VerificationResult:
    accepted: bool
    flagged: bool            # true when accepted under grace — must be logged
    reason: str


def verify_delegation(
    token: DelegatedToken,
    trust_store: Dict[str, Anchor],
    now: Optional[float] = None,
) -> VerificationResult:
    now = now if now is not None else time.time()

    if token.exp <= now:
        raise AnchorDiscontinuityError(
            f"token expired at {token.exp}, now={now}"
        )

    anchor = trust_store.get(token.anchor_id)

    if anchor is None:
        # Not an auth failure — the verifier's trust store is out of sync
        # with the issuer's rotation. Escalate as an operational fault.
        raise TrustStoreDesyncError(
            f"anchor {token.anchor_id!r} unknown to trust store; "
            f"possible rotation desync, not a signature failure"
        )

    if anchor.disposition is AnchorDisposition.REVOKED:
        # Compromise-driven re-anchor: reject hard, signal re-mint.
        raise AnchorDiscontinuityError(
            f"anchor {anchor.anchor_id!r} revoked (compromise); "
            f"holder must re-mint delegation under current active anchor"
        )

    if anchor.disposition is AnchorDisposition.ACTIVE:
        return VerificationResult(accepted=True, flagged=False, reason="active anchor")

    if anchor.disposition is AnchorDisposition.GRACE:
        if anchor.grace_until is None or now >= anchor.grace_until:
            raise AnchorDiscontinuityError(
                f"anchor {anchor.anchor_id!r} grace window closed at "
                f"{anchor.grace_until}, now={now}"
            )
        # Accept but flag: this token was minted under a retired anchor.
        return VerificationResult(
            accepted=True,
            flagged=True,
            reason=f"accepted under grace until {anchor.grace_until}",
        )

    raise AnchorDiscontinuityError(
        f"anchor {anchor.anchor_id!r} in unhandled disposition {anchor.disposition}"
    )


def handoff(token: DelegatedToken, trust_store: Dict[str, Anchor]) -> VerificationResult:
    result = verify_delegation(token, trust_store)
    if result.flagged:
        # Downstream audit MUST record the discontinuity, not swallow it.
        _emit_audit("anchor_grace_accept", token.anchor_id, result.reason)
    return result


def _emit_audit(event: str, anchor_id: str, detail: str) -> None:
    # Placeholder for the audit sink; must be durable and ordered.
    pass
