# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-peer-whose-spiffe-svid-chains-to-a-trusted-root-but-whose-verifiable-credential-subject-bind.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-peer-whose-spiffe-svid-chains-to-a-trusted-root-but-whose-verifiable-credential-subject-bind.warrant.json
# Markdown SHA-256:   204411b7a12c939e8d27ff91f6f6ae2da7d0bd6bc8b3017365f0248843631134
# Code AST SHA-256:   5d572ab373c229f13e7ddb745b583f48d023978804bc181d0f127f04e36190c5
# Verified Classes:   SplitValidityError, SelectorSnapshot, SVID, VerifiableCredential
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SplitValidityError(RuntimeError):
    """Raised when SVID+VC are each valid but their binding is not."""


@dataclass(frozen=True)
class SelectorSnapshot:
    set_hash: str
    selectors: frozenset
    monotonic_counter: int
    residual_scopes: Optional[frozenset] = None  # non-None => draining


@dataclass(frozen=True)
class SVID:
    spiffe_id: str
    selector: str
    not_after: float


@dataclass(frozen=True)
class VerifiableCredential:
    subject_id: str
    issued_at: float
    issued_at_counter: Optional[int]
    selector_set_hash: Optional[str]
    expiration: float


def verify_federated_handoff(
    svid: SVID,
    vc: VerifiableCredential,
    issuer_history: dict,          # set_hash -> SelectorSnapshot
    issuer_current: SelectorSnapshot,
    max_skew_seconds: float,
    verifier_now: float,
    requested_scopes: frozenset,
) -> frozenset:
    # 1. Subject binding must be exact.
    if svid.spiffe_id != vc.subject_id:
        raise SplitValidityError(
            f"subject mismatch: svid={svid.spiffe_id} vc={vc.subject_id}"
        )

    # 2. VC must commit to a selector-set snapshot. Absence is disqualifying.
    if not vc.selector_set_hash:
        raise SplitValidityError(
            "VC carries no selector_set_hash commitment; binding is unfalsifiable"
        )

    snapshot = issuer_history.get(vc.selector_set_hash)
    if snapshot is None:
        raise SplitValidityError(
            f"VC commits to unknown snapshot {vc.selector_set_hash}"
        )

    # 3. Resolve snapshot by monotonic counter when available (clock-skew immune).
    if vc.issued_at_counter is not None:
        if snapshot.monotonic_counter != vc.issued_at_counter:
            raise SplitValidityError(
                "counter/hash disagreement: VC minted against different snapshot"
            )
    else:
        if abs(verifier_now - vc.issued_at) > max_skew_seconds:
            # Cannot disambiguate issued_at against adjacent snapshots.
            raise SplitValidityError(
                f"issued_at ambiguous under skew bound: "
                f"delta={abs(verifier_now - vc.issued_at):.1f}s"
            )

    # 4. The SVID's selector must be in the snapshot the VC was minted against.
    if svid.selector not in snapshot.selectors:
        raise SplitValidityError(
            f"selector {svid.selector!r} not in VC-committed snapshot "
            f"{snapshot.set_hash}"
        )

    # 5. The current set must NOT be used to grant authority. Guard against
    #    accidental reliance on it: if the selector is only in current and not
    #    in the committed snapshot, step 4 already failed. Here we only check
    #    that current set does not *silently broaden* the snapshot.
    if svid.selector in issuer_current.selectors and svid.selector not in snapshot.selectors:
        # unreachable given step 4, but asserted for auditability
        raise SplitValidityError("current-set leakage into binding predicate")

    # 6. Drain grace yields degraded scope, not full rejection, not full grant.
    effective = snapshot.residual_scopes
    if effective is not None:
        granted = requested_scopes & effective
        if not granted:
            raise SplitValidityError(
                f"draining snapshot {snapshot.set_hash} grants no "
                f"requested scope {sorted(requested_scopes)}"
            )
        return granted

    # 7. Bound warrant by both lifetimes.
    if min(svid.not_after, vc.expiration) <= verifier_now:
        raise SplitValidityError("combined artifact lifetime exhausted")

    return requested_scopes
