# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-is-locally-valid-but-whose-cross-issuer-trust-anchor-has-b.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-chain-is-locally-valid-but-whose-cross-issuer-trust-anchor-has-b.warrant.json
# Markdown SHA-256:   1426be4093dec75f432258f814287bfc6612741519bd59b43540823f66537fa7
# Code AST SHA-256:   36fd72ef3364da342954bb4e74b92b7cfc270ff5875a6a2b1c828f64824f6917
# Verified Classes:   ZombieChainError, AnchorRecord, Hop, DelegatedCredential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Literal

AnchorState = Literal["active", "superseded", "revoked"]


class ZombieChainError(RuntimeError):
    """Raised when a delegated AAIF chain is locally valid but its root
    trust anchor has been superseded past its grace window, or when the
    chain's provenance set is incomplete and cannot be resolved."""


@dataclass
class AnchorRecord:
    key_id: str
    state: AnchorState
    superseded_at: float | None = None
    grace_until: float | None = None


@dataclass
class Hop:
    issuer_anchor: str          # anchor key this hop was signed under
    signing_time: float
    scope: str


@dataclass
class DelegatedCredential:
    hops: list[Hop]
    provenance: list[str] = field(default_factory=list)  # accumulated anchor ids


def resolve_anchor(anchor_id: str, trust_store: dict[str, AnchorRecord]) -> AnchorRecord:
    rec = trust_store.get(anchor_id)
    if rec is None:
        raise ZombieChainError(f"anchor {anchor_id!r} not present in trust store")
    return rec


def anchor_admissible(rec: AnchorRecord, signing_time: float, now: float) -> bool:
    # Must be valid at signing time...
    if rec.state == "revoked":
        return False
    if rec.state == "superseded" and rec.superseded_at is not None:
        if signing_time >= rec.superseded_at:
            return False  # signed under an anchor already superseded -> forged/stale
        # ...and valid at verification time, allowing the grace window.
        if rec.grace_until is not None and now >= rec.grace_until:
            return False  # grace expired -> zombie chain
    return True


def verify_chain(
    cred: DelegatedCredential,
    trust_store: dict[str, AnchorRecord],
    now: float | None = None,
) -> None:
    now = now if now is not None else time.time()

    referenced = {h.issuer_anchor for h in cred.hops}
    declared = set(cred.provenance)

    # Provenance completeness: every anchor referenced by a hop must be
    # declared, otherwise the chain may be truncated and we cannot know
    # whether an upstream root anchor was dropped.
    missing = referenced - declared
    if missing:
        raise ZombieChainError(
            f"incomplete provenance: hops reference anchors {sorted(missing)} "
            f"not present in provenance set {sorted(declared)}"
        )

    # Per-hop anchor resolution. Leaf-only verification is the observed bug;
    # we assert cardinality of resolved anchors equals distinct references.
    resolved: set[str] = set()
    for i, hop in enumerate(cred.hops):
        rec = resolve_anchor(hop.issuer_anchor, trust_store)
        if not anchor_admissible(rec, hop.signing_time, now):
            raise ZombieChainError(
                f"hop {i} anchored at {hop.issuer_anchor!r} is inadmissible: "
                f"state={rec.state} superseded_at={rec.superseded_at} "
                f"grace_until={rec.grace_until} now={now}"
            )
        resolved.add(hop.issuer_anchor)

    if resolved != referenced:
        # Defensive: should be impossible after the loop, but the invariant
        # is what makes the failure detectable from logs and traces.
        raise ZombieChainError(
            f"anchor resolution cardinality mismatch: resolved {sorted(resolved)} "
            f"!= referenced {sorted(referenced)}"
        )


def admit_request(cred: DelegatedCredential, trust_store: dict[str, AnchorRecord]) -> str:
    try:
        verify_chain(cred, trust_store)
    except ZombieChainError as exc:
        # Fail closed with a distinct class so operators can distinguish
        # truncated / orphaned / forged chains in telemetry.
        raise ZombieChainError(f"AAIF admission denied: {exc}") from exc
    return "admitted"
