# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-aaif-attestation-credential-as-unusable-at-the-moment-of-a-delegated-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-aaif-attestation-credential-as-unusable-at-the-moment-of-a-delegated-tool-call.warrant.json
# Markdown SHA-256:   e598c2e033434a587b0c3c8823e0d1c883eafc68a3256102cc49e142b9cdeda3
# Code AST SHA-256:   ee4f9bbc6280cf3b32d61bb9c8edb1dd476e9ce8c8aa132a3ad3780f48de8058
# Verified Classes:   CredentialUnusableForEndpoint, VerifiableCredential, CredentialLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Optional


class CredentialUnusableForEndpoint(RuntimeError):
    """Raised when a cryptographically valid VC cannot be used for a specific call."""


@dataclass(frozen=True)
class VerifiableCredential:
    serial: str
    issuer: str
    subject: str
    audience: frozenset[str]
    scope: frozenset[str]
    cnf_public_key: str          # PoP public key bound into the credential
    nbf: float
    exp: float
    revoked: bool = False


@dataclass
class CredentialLedger:
    """Parent-side record of what was minted for which endpoint."""
    entries: dict[str, dict] = field(default_factory=dict)

    def record(self, vc: VerifiableCredential, child_instance: str) -> None:
        self.entries[vc.serial] = {
            "audience": vc.audience,
            "scope": vc.scope,
            "child": child_instance,
        }

    def re_mint_audience_for(self, serial: str, endpoint_id: str) -> frozenset[str]:
        prior = self.entries.get(serial)
        if prior is None:
            raise CredentialUnusableForEndpoint(
                f"no ledger entry for {serial}; cannot re-mint safely"
            )
        return prior["audience"] | {endpoint_id}


def assert_usable_for_endpoint(
    vc: VerifiableCredential,
    endpoint_id: str,
    endpoint_required_scope: frozenset[str],
    caller_controlled_keys: frozenset[str],
    now: Optional[float] = None,
) -> None:
    """Local pre-call usability gate. Raises on any clause failure; never retries."""
    now = time.time() if now is None else now

    if vc.revoked:
        raise CredentialUnusableForEndpoint(f"{vc.serial}: revoked")
    if not (vc.nbf <= now < vc.exp):
        raise CredentialUnusableForEndpoint(
            f"{vc.serial}: outside validity window ({vc.nbf}..{vc.exp}, now={now})"
        )
    if endpoint_id not in vc.audience:
        # Deterministic audience rejection: retrying is always wrong.
        raise CredentialUnusableForEndpoint(
            f"{vc.serial}: audience {sorted(vc.audience)} does not contain "
            f"endpoint {endpoint_id!r}; request re-mint, do not retry"
        )
    if not endpoint_required_scope.issubset(vc.scope):
        raise CredentialUnusableForEndpoint(
            f"{vc.serial}: scope {sorted(vc.scope)} lacks required "
            f"{sorted(endpoint_required_scope - vc.scope)}"
        )
    if vc.cnf_public_key not in caller_controlled_keys:
        # Post-handoff binding failure: credential travelled, PoP key did not.
        raise CredentialUnusableForEndpoint(
            f"{vc.serial}: PoP key {vc.cnf_public_key!r} not held by this "
            f"instance; credential unusable after handoff"
        )


def call_tool(
    vc: VerifiableCredential,
    endpoint_id: str,
    endpoint_required_scope: frozenset[str],
    caller_controlled_keys: frozenset[str],
) -> str:
    assert_usable_for_endpoint(
        vc, endpoint_id, endpoint_required_scope, caller_controlled_keys
    )
    return f"200 OK: called {endpoint_id} with {vc.serial}"


if __name__ == "__main__":
    now = time.time()
    ledger = CredentialLedger()
    vc = VerifiableCredential(
        serial="vc-001",
        issuer="orchestrator",
        subject="worker-W",
        audience=frozenset({"retrieval.tools.example"}),
        scope=frozenset({"docs:read"}),
        cnf_public_key="pk_w",
        nbf=now - 10,
        exp=now + 120,
    )
    ledger.record(vc, child_instance="worker-W")

    # Correct call path.
    print(call_tool(vc, "retrieval.tools.example", frozenset({"docs:read"}), frozenset({"pk_w"})))

    # Mis-audienced second call: gate raises locally, no wasted round-trip.
    try:
        call_tool(vc, "summarizer.internal", frozenset({"docs:read"}), frozenset({"pk_w"}))
    except CredentialUnusableForEndpoint as e:
        print("blocked:", e)
        new_aud = ledger.re_mint_audience_for(vc.serial, "summarizer.internal")
        print("re-mint audience:", sorted(new_aud))
