# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-agent-credential-whose-did-binding-was-valid-at-issuance-but-whose-controller-key-rotated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-agent-credential-whose-did-binding-was-valid-at-issuance-but-whose-controller-key-rotated-mid-handoff.warrant.json
# Markdown SHA-256:   7f6ec00ed231deb477808ac5cb16f1f4a14ca1defd3b3486ea2c372e587be0eb
# Code AST SHA-256:   73b57d943dbdc3cae065beaaa2dc888196eb358aa030b198dacaad0fbed50e40
# Verified Classes:   BindingDiscontinuityError, StaleResolutionError, VerificationMethod, DIDDocument, Credential
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional


class BindingDiscontinuityError(RuntimeError):
    """Raised when a credential's proof key is no longer authoritative at presentation time."""
    pass


class StaleResolutionError(RuntimeError):
    """Raised when the DID document cannot be resolved within the freshness window."""
    pass


@dataclass
class VerificationMethod:
    id: str
    controller: str
    deactivated: bool
    relationships: set[str]  # e.g. {"capabilityInvocation", "authentication"}


@dataclass
class DIDDocument:
    did: str
    version_id: int
    updated: datetime
    methods: dict[str, VerificationMethod]


@dataclass
class Credential:
    subject_did: str
    issuer_did: str
    proof_method_id: str          # e.g. "did:web:agent-a#K1"
    proof_purpose: str            # e.g. "capabilityInvocation"
    issuance_date: datetime
    expiration_date: datetime
    revoked: bool
    scope: str


FRESHNESS_WINDOW = timedelta(seconds=30)


def verify_federated_credential(
    cred: Credential,
    resolved_subject_doc: Optional[DIDDocument],
    resolved_at: datetime,
    now: datetime,
    expected_controller: str,
) -> None:
    # 1. Temporal envelope
    if cred.revoked:
        raise BindingDiscontinuityError(f"credential {cred.scope} revoked")
    if not (cred.issuance_date <= now <= cred.expiration_date):
        raise BindingDiscontinuityError("credential outside validity window")

    # 2. Fresh resolution — never fall back to cache to keep a handoff moving
    if resolved_subject_doc is None:
        raise StaleResolutionError(
            f"cannot resolve {cred.subject_did}; suspend handoff, do not reuse cache"
        )
    if now - resolved_at > FRESHNESS_WINDOW:
        raise StaleResolutionError(
            f"DID doc for {cred.subject_did} resolved {now - resolved_at} ago; "
            f"exceeds {FRESHNESS_WINDOW}; re-resolve before authorizing"
        )

    # 3. Binding must be present-tense: key active AND in the required relationship
    method = resolved_subject_doc.methods.get(cred.proof_method_id)
    if method is None:
        raise BindingDiscontinuityError(
            f"proof method {cred.proof_method_id} absent from current DID document"
        )
    if method.deactivated:
        # The exact failure: envelope verifies, but key is a tombstone.
        raise BindingDiscontinuityError(
            f"proof method {cred.proof_method_id} is deactivated at presentation; "
            f"controller rotated mid-handoff — require reissued credential under active key"
        )
    if cred.proof_purpose not in method.relationships:
        raise BindingDiscontinuityError(
            f"proof method {cred.proof_method_id} lacks relationship "
            f"'{cred.proof_purpose}' (has {method.relationships})"
        )

    # 4. Controller must match the federation trust policy for this scope
    if method.controller != expected_controller:
        raise BindingDiscontinuityError(
            f"controller {method.controller} != expected {expected_controller} "
            f"for scope {cred.scope}"
        )

    # 5. Document must not predate issuance (guards against stale-doc replay)
    if resolved_subject_doc.updated < cred.issuance_date:
        raise StaleResolutionError(
            "resolved DID document predates credential issuance; re-resolve"
        )


def handle_handoff(cred: Credential, doc: Optional[DIDDocument], resolved_at: datetime,
                   now: datetime, expected_controller: str) -> str:
    try:
        verify_federated_credential(cred, doc, resolved_at, now, expected_controller)
    except StaleResolutionError as e:
        return f"SUSPEND: {e}"  # do not degrade to cached authorization
    except BindingDiscontinuityError as e:
        return f"REJECT: {e}"
    return "ACCEPT"
