# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-warrant-whose-attestation-chain-is-valid-but-whose-trust-root-was-re-signed-mid-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-warrant-whose-attestation-chain-is-valid-but-whose-trust-root-was-re-signed-mid-federation.warrant.json
# Markdown SHA-256:   7475f6d3e74258b591dcc6be23b3e587ad33f1d0cb6f74131ca06af6b7a3f2c6
# Code AST SHA-256:   1cba486d0534c2ef92c9f99239b26a8439e03eb9138ce3c2a5c3b18a60562c36
# Verified Classes:   WarrantAdmissibilityError, DelegationStatement, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantAdmissibilityError(RuntimeError):
    """Raised when a brokered capability warrant cannot be proven admissible."""
    pass


@dataclass(frozen=True)
class DelegationStatement:
    anchor_id: str
    valid_from: int          # epoch seconds
    valid_to: int            # epoch seconds
    delegation_set: frozenset[str]
    signature: bytes

    def covers(self, scope: str, mint_time: int) -> bool:
        return (
            self.valid_from <= mint_time <= self.valid_to
            and scope in self.delegation_set
        )


@dataclass(frozen=True)
class Warrant:
    leaf_key: str
    claimed_scope: str
    mint_time: int
    anchor_id: str
    chain_signatures_valid: bool
    delegation_statement_hash: Optional[str]


def verify_warrant_admissibility(
    warrant: Warrant,
    trusted_anchors: dict[str, bytes],
    delegation_statements: dict[str, DelegationStatement],
    verifier_statement_fetch_time: int,
) -> None:
    # Step 1: chain must verify. This is necessary but NOT sufficient.
    if not warrant.chain_signatures_valid:
        raise WarrantAdmissibilityError(
            f"attestation chain does not verify for leaf {warrant.leaf_key}"
        )

    # Step 2: anchor must be currently trusted.
    if warrant.anchor_id not in trusted_anchors:
        raise WarrantAdmissibilityError(
            f"anchor {warrant.anchor_id} not in trusted anchor set"
        )

    # Step 3: the critical boundary check. A valid chain rooted in a trusted
    # anchor is NOT admissible unless a time-and-scope-bound delegation
    # assertion proves the anchor was authorized to delegate this scope at
    # the warrant's mint time. Absence of the assertion is refusal, not admit.
    if warrant.delegation_statement_hash is None:
        raise WarrantAdmissibilityError(
            f"warrant for scope {warrant.claimed_scope!r} carries no delegation "
            f"assertion; admissibility cannot be established during rotation"
        )

    stmt = delegation_statements.get(warrant.delegation_statement_hash)
    if stmt is None:
        raise WarrantAdmissibilityError(
            f"delegation statement {warrant.delegation_statement_hash} unavailable "
            f"to verifier; refusing rather than admitting on trust-store presence"
        )

    # Step 4: statement must be signed by the anchor it describes.
    expected_sig = hashlib.sha256(
        f"{stmt.anchor_id}:{stmt.valid_from}:{stmt.valid_to}:"
        f"{sorted(stmt.delegation_set)}".encode()
    ).digest()
    if stmt.signature != expected_sig:
        raise WarrantAdmissibilityError(
            f"delegation statement signature invalid for anchor {stmt.anchor_id}"
        )

    # Step 5: statement must actually cover this warrant's scope at mint time.
    # This is what catches the scope-narrowing rotation: R_old's statement
    # excludes the narrowed scope, so an R_old-rooted warrant claiming it fails
    # here even though its chain verified against a still-trusted R_old.
    if not stmt.covers(warrant.claimed_scope, warrant.mint_time):
        raise WarrantAdmissibilityError(
            f"anchor {stmt.anchor_id} not authorized to delegate scope "
            f"{warrant.claimed_scope!r} at mint_time {warrant.mint_time}; "
            f"delegation window {stmt.valid_from}..{stmt.valid_to} "
            f"excludes it (scope-narrowing rotation)"
        )

    # Step 6: freshness. A stale statement must not admit warrants minted
    # after the verifier's last fetch, or the narrowing can be bypassed.
    if warrant.mint_time > verifier_statement_fetch_time:
        raise WarrantAdmissibilityError(
            f"warrant mint_time {warrant.mint_time} exceeds verifier statement "
            f"fetch time {verifier_statement_fetch_time}; statement may be stale"
        )


def admit_or_refuse(warrant: Warrant, **kwargs) -> str:
    try:
        verify_warrant_admissibility(warrant, **kwargs)
    except WarrantAdmissibilityError as exc:
        return f"REFUSED: {exc}"
    return f"ADMITTED: scope {warrant.claimed_scope!r} under {warrant.anchor_id}"
