# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-delegated-capability-across-a-federation-trust-seam-when-the-delegating-peer-s-policy-document-is-syntactical.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-inherit-delegated-capability-across-a-federation-trust-seam-when-the-delegating-peer-s-policy-document-is-syntactical.warrant.json
# Markdown SHA-256:   803b9ffa7350a65598a4fd37aba96935eeac2e847710d87a087d217a6c54cbd2
# Code AST SHA-256:   cac2abce090d0207238687b020664cb593b941f85c8d182309e7caa14fdd69b2
# Verified Classes:   StalePolicyAdmissionError, Policy, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class StalePolicyAdmissionError(RuntimeError):
    """Raised when a delegated warrant is exercised against a policy that no
    longer admits its (capability, resource_scope, depth, principal) tuple."""


@dataclass(frozen=True)
class Policy:
    etag: str
    semantic_hash: str
    resource_scope: frozenset
    max_delegation_depth: int
    revoked_warrants: frozenset


@dataclass(frozen=True)
class Warrant:
    capability: str
    resource: str
    delegation_depth: int
    principal: str
    policy_semantic_hash: str
    issued_at: float
    valid_for: float


def semantic_hash_of(policy_doc: dict) -> str:
    material = "|".join(
        [
            ",".join(sorted(policy_doc["resource_scope"])),
            str(policy_doc["max_delegation_depth"]),
            ",".join(sorted(policy_doc["revoked_warrants"])),
        ]
    )
    return hashlib.sha256(material.encode()).hexdigest()


def admit_warrant(
    warrant: Warrant,
    live_policy: Policy,
    max_policy_age: float,
    now: Optional[float] = None,
) -> None:
    now = time.time() if now is None else now

    # Provenance (signature) is assumed verified upstream. This function answers
    # only the currency question: does the *live* policy still admit the tuple?
    if warrant.delegation_depth > live_policy.max_delegation_depth:
        raise StalePolicyAdmissionError(
            f"depth {warrant.delegation_depth} exceeds live max "
            f"{live_policy.max_delegation_depth} (warrant minted under "
            f"semantic_hash {warrant.policy_semantic_hash[:12]})"
        )

    if warrant.resource not in live_policy.resource_scope:
        raise StalePolicyAdmissionError(
            f"resource {warrant.resource!r} not in live resource_scope; "
            f"warrant's policy_hash {warrant.policy_semantic_hash[:12]} != "
            f"live {live_policy.semantic_hash[:12]}"
        )

    if warrant.principal in live_policy.revoked_warrants:
        raise StalePolicyAdmissionError(
            f"principal {warrant.principal!r} revoked under live policy "
            f"{live_policy.etag}"
        )

    # If the semantic hash matches, the warrant's backing policy is current.
    # If it differs, we have positively re-admitted above; record the drift.
    if warrant.policy_semantic_hash != live_policy.semantic_hash:
        age = now - warrant.issued_at
        if age > max_policy_age:
            raise StalePolicyAdmissionError(
                f"warrant age {age:.1f}s exceeds max_policy_age "
                f"{max_policy_age:.1f}s and policy semantic_hash drifted "
                f"({warrant.policy_semantic_hash[:12]} -> "
                f"{live_policy.semantic_hash[:12]}); re-issuance required"
            )
