# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-credential-whose-subject-binding-no-longer-matches-the-live-agent-process.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-credential-whose-subject-binding-no-longer-matches-the-live-agent-process.warrant.json
# Markdown SHA-256:   fcbdc7ae6764407c38b7591f0b5cc9c1c468f0ae5d348d6f89c13716085d68b2
# Code AST SHA-256:   e7c726d630274ef254c03f509e44c8deb66366f098421c48c1af28bf5bfbb9df
# Verified Classes:   BindingMismatchError, InvalidCredentialError, AACredential
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BindingMismatchError(RuntimeError):
    """Credential is valid, but the presenting process is not its bound subject."""
    pass


class InvalidCredentialError(RuntimeError):
    """Signature or status failure: credential itself is not trustworthy."""
    pass


@dataclass(frozen=True)
class AACredential:
    agent_id: str
    binding_commitment: str  # hex digest
    valid: bool               # signature + status list already checked


def compute_binding(process_nonce: bytes, key_thumbprint: bytes) -> str:
    return hashlib.sha256(process_nonce + b"|" + key_thumbprint).hexdigest()


def authorize(cred: AACredential, live_nonce: bytes, live_thumbprint: bytes) -> str:
    if not cred.valid:
        raise InvalidCredentialError(
            f"credential for {cred.agent_id} failed signature/status check"
        )

    live = compute_binding(live_nonce, live_thumbprint)
    if live != cred.binding_commitment:
        # Terminal for THIS instance. Do not requeue the same credential.
        raise BindingMismatchError(
            f"binding mismatch for {cred.agent_id}: "
            f"credential bound to {cred.binding_commitment[:12]}..., "
            f"presenting process is {live[:12]}..."
        )

    return f"authorized:{cred.agent_id}"
