# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-did-key-binding-divergence-during-cross-org-federated-agent-identity-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-did-key-binding-divergence-during-cross-org-federated-agent-identity-resolution.warrant.json
# Markdown SHA-256:   bd04f6dfe5f03ada88ea20bdc6cba62c47c18e8b547b5f13a190e915f7c732e5
# Code AST SHA-256:   cddac7b70e3a143d4241ae009dd88ccef1782a2ac362f064713f751aa502462f
# Verified Classes:   KeyBindingDivergence, DidDocument
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class KeyBindingDivergence(RuntimeError):
    """Raised when a VC's proof key is resolvable but not authorized for the required relationship."""


@dataclass
class DidDocument:
    did: str
    updated: float
    verification_method: dict  # key_id -> public_key_jwk
    authentication: list       # key_ids
    assertion_method: list     # key_ids
    capability_invocation: list  # key_ids
    revoked: set               # key_ids


REQUIRED_RELATIONSHIP = {
    "assertion": "assertion_method",
    "authentication": "authentication",
    "capability": "capability_invocation",
}


def check_binding(
    doc: DidDocument,
    proof_key_id: str,
    vc_issuance: float,
    required_relationship: str,
    clock_skew: float = 60.0,
) -> None:
    # 1. Key must exist in the document.
    if proof_key_id not in doc.verification_method:
        raise KeyBindingDivergence(
            f"proof key {proof_key_id} absent from verificationMethod of {doc.did}"
        )

    # 2. Key must be a member of the relationship array required by VC semantics.
    rel_attr = REQUIRED_RELATIONSHIP[required_relationship]
    authorized = getattr(doc, rel_attr)
    if proof_key_id not in authorized:
        diff = set(doc.verification_method) - set(
            doc.authentication + doc.assertion_method + doc.capability_invocation
        )
        raise KeyBindingDivergence(
            f"proof key {proof_key_id} resolvable but not in {rel_attr}; "
            f"unbound keys present in document: {sorted(diff)}"
        )

    # 3. Document must not predate the credential (stale-binding guard).
    if doc.updated + clock_skew < vc_issuance:
        raise KeyBindingDivergence(
            f"resolved document updated={doc.updated} predates vc issuance={vc_issuance}; "
            f"binding state is stale"
        )

    # 4. Key must not be revoked.
    if proof_key_id in doc.revoked:
        raise KeyBindingDivergence(f"proof key {proof_key_id} is revoked in {doc.did}")


def verify_and_grant(doc, proof_key_id, vc_issuance, relationship, capability):
    check_binding(doc, proof_key_id, vc_issuance, relationship)
    return {"granted": capability, "key": proof_key_id, "at": time.time()}
