# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-a2a-peer-warrant-as-still-valid-transitive-trust-and-how-does-revocation-propagation-fail-across-fe.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-a2a-peer-warrant-as-still-valid-transitive-trust-and-how-does-revocation-propagation-fail-across-fe.warrant.json
# Markdown SHA-256:   c90e5a4646cbd54d9f8c5960650d25cbf5ae1c95a9252a8ad84321bec71cc664
# Code AST SHA-256:   f83cc78586bc06c7598b97f27a7998c17d0aba915f73ef1f08c3898708c474cb
# Verified Classes:   RevocationChainIndeterminate, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class RevocationChainIndeterminate(RuntimeError):
    """Raised when a warrant's embedded chain cannot be established as un-revoked.

    This is a hard-deny signal: the admission must be refused, not defaulted
    to allow, because the invariant 'every chain issuer un-revoked at mint and
    at verification' could not be confirmed.
    """


@dataclass
class Warrant:
    jti: str
    issuer: str
    subject: str
    parent_delegation_ref: Optional[str]  # hash or jti of the parent warrant
    iat: float
    exp: float
    chain: list  # embedded parent warrants, leaf-first


def _canonical_hash(w: Warrant) -> str:
    body = json.dumps(
        {"jti": w.jti, "issuer": w.issuer, "subject": w.subject, "iat": w.iat},
        sort_keys=True,
        separators=(",", ":"),
    ).encode()
    return hashlib.sha256(body).hexdigest()


def verify_chain_revocation(
    leaf: Warrant,
    status_lookup,          # issuer_id -> set of revoked parent_delegation_refs
    max_status_age_s: float,
    now: float,
    status_fetched_at: dict,  # issuer_id -> timestamp of last successful fetch
) -> None:
    """Enforce chain-anchored revocation across the full embedded chain.

    Raises RevocationChainIndeterminate on any of:
      - missing parent linkage on a non-root warrant
      - a parent_delegation_ref present in an issuer's revocation set
      - an issuer status older than max_status_age_s (unknown != valid)
    """
    nodes = [leaf] + list(leaf.chain)

    for idx, node in enumerate(nodes):
        is_root = idx == len(nodes) - 1
        if not is_root and node.parent_delegation_ref is None:
            raise RevocationChainIndeterminate(
                f"warrant {node.jti} from {node.issuer} lacks parent_delegation_ref; "
                "cannot attribute upstream revocation to this warrant (fail-closed)"
            )

        fetched = status_fetched_at.get(node.issuer)
        if fetched is None or (now - fetched) > max_status_age_s:
            raise RevocationChainIndeterminate(
                f"revocation status for issuer {node.issuer} is unknown or stale "
                f"(age={None if fetched is None else now - fetched:.1f}s, "
                f"max={max_status_age_s:.1f}s); unknown is not valid"
            )

        revoked = status_lookup(node.issuer)
        if node.parent_delegation_ref is not None and node.parent_delegation_ref in revoked:
            raise RevocationChainIndeterminate(
                f"parent delegation {node.parent_delegation_ref} revoked by "
                f"{node.issuer} at verification time {now}; chain is dead"
            )

    # Cross-check that each child's parent ref actually names the next node up.
    for idx in range(len(nodes) - 1):
        child, parent = nodes[idx], nodes[idx + 1]
        if child.parent_delegation_ref != _canonical_hash(parent):
            raise RevocationChainIndeterminate(
                f"parent linkage mismatch: {child.jti} claims "
                f"{child.parent_delegation_ref}, computed {_canonical_hash(parent)}"
            )
