# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capabilities-pushnotifications-is-true-but-whose-securityschemes-omits-the-webhook-verificatio.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-agent-card-whose-capabilities-pushnotifications-is-true-but-whose-securityschemes-omits-the-webhook-verificatio.warrant.json
# Markdown SHA-256:   44959e3c76d883287bbc0646e1a0e4feba59ddef98e8398319108f76733cc8e2
# Code AST SHA-256:   fc9903967484cdb39ece5e14d601e8775415769f0a0d625cf65367eb370027d4
# Verified Classes:   PushCapabilityIncoherenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from typing import Any


class PushCapabilityIncoherenceError(RuntimeError):
    """Raised when a signed Agent Card advertises pushNotifications but
    declares no resolvable callback-authentication material, making any
    webhook registration unverifiable (and the task state machine forgeable)."""


# Scheme types that can authenticate an *outbound* callback FROM the worker
# TO the client. Inbound-only schemes (e.g. plain http bearer for callers)
# do NOT satisfy this — directionality is the whole point.
CALLBACK_AUTH_SCHEME_TYPES = frozenset({"webhook-signature", "hmac", "jws-callback"})


def _has_resolvable_callback_auth(card: dict[str, Any]) -> bool:
    schemes = card.get("securitySchemes") or {}
    for name, spec in schemes.items():
        if not isinstance(spec, dict):
            continue
        if spec.get("type") in CALLBACK_AUTH_SCHEME_TYPES:
            # Material must be named, not implied.
            if spec.get("jwks_uri") or spec.get("secretRef") or spec.get("keyRef"):
                return True
    return False


def gate_push_registration(card: dict[str, Any], signature_verified: bool) -> str:
    """Decide whether a verified Agent Card may be used to register a webhook.

    Returns one of: 'register', 'downshift-poll', 'provision-error'.
    """
    if not signature_verified:
        raise PushCapabilityIncoherenceError(
            "refusing to evaluate capability on an unverified card"
        )

    caps = card.get("capabilities") or {}
    advertises_push = bool(caps.get("pushNotifications"))

    if not advertises_push:
        return "register"  # nothing to provision; polling is the default anyway

    if _has_resolvable_callback_auth(card):
        return "register"

    # Signed, push-advertising, but no callback-auth material: the exact
    # incoherence boundary. Do NOT register-and-hope.
    agent_name = card.get("name", "<unnamed>")
    raise PushCapabilityIncoherenceError(
        f"agent {agent_name!r} advertises pushNotifications=true but declares "
        f"no callback-auth scheme (types {sorted(CALLBACK_AUTH_SCHEME_TYPES)} "
        f"with resolvable material). Downshift to polling; do not register a "
        f"webhook whose callbacks cannot be verified."
    )


def resolve_and_provision(card_json: str, signature_verified: bool) -> str:
    card = json.loads(card_json)
    try:
        return gate_push_registration(card, signature_verified)
    except PushCapabilityIncoherenceError:
        # Explicit, recorded downshift — never a silent fallback.
        return "downshift-poll"
