# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-did-document-rotates-its-verification-method-mid-federation-without-re-anchoring-the-credential-s-credentialsubject-bi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-did-document-rotates-its-verification-method-mid-federation-without-re-anchoring-the-credential-s-credentialsubject-bi.warrant.json
# Markdown SHA-256:   d4ff91241b93145e4b58128ed32236a4b9c8f14215fbd075b413fc4baa9e8776
# Code AST SHA-256:   229fdf6a05ca49200d658f71a44a6a2113fa7fbcc489f7926bf646fd9879c4bb
# Verified Classes:   DidBindingError, VerificationMethod, DidDocument, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class DidBindingError(RuntimeError):
    """Raised when a credential's subject binding cannot be anchored to a
    specific, still-present verification method at verification time."""


@dataclass
class VerificationMethod:
    id: str            # e.g. "did:example:agent-7#key-1"
    public_key: str
    deactivated: bool = False


@dataclass
class DidDocument:
    did: str
    methods: dict = field(default_factory=dict)   # id -> VerificationMethod
    version: int = 0

    def resolve(self) -> "DidDocument":
        # Live resolution: returns *current* state, which may have rotated.
        return self


@dataclass
class Credential:
    issuer_did: str
    subject_did: str
    # CRITICAL: if this is None, the credential is only slot-bound (Posture B).
    bound_method_id: Optional[str]
    scope: list
    signature: str


def verify_and_authorize(
    cred: Credential,
    presenting_method_id: str,
    subject_doc: DidDocument,
    issuer_doc: DidDocument,
    decision_log: dict,
) -> bool:
    # 1. Issuer proof validity (unchanged by subject rotation).
    if cred.issuer_did != issuer_doc.did:
        raise DidBindingError(
            f"issuer DID mismatch: cred={cred.issuer_did} resolved={issuer_doc.did}"
        )

    # 2. Subject binding: MUST be method-ID bound, not bare-DID bound.
    if cred.bound_method_id is None:
        raise DidBindingError(
            "credential is slot-bound (no verificationMethod ID); "
            "refusing to grant under instance-binding policy"
        )

    # 3. The bound method must still exist and be live in the resolved doc.
    method = subject_doc.methods.get(cred.bound_method_id)
    if method is None:
        raise DidBindingError(
            f"bound method {cred.bound_method_id} absent from resolved DID document "
            f"(rotated/removed); credential cannot be re-anchored to current key"
        )
    if method.deactivated:
        raise DidBindingError(
            f"bound method {cred.bound_method_id} is deactivated; "
            "re-issuance required"
        )

    # 4. The presenter must be the *same* method the credential was bound to.
    if presenting_method_id != cred.bound_method_id:
        raise DidBindingError(
            f"presenter {presenting_method_id} != bound method {cred.bound_method_id}; "
            "rotation transferred slot, not instance"
        )

    # 5. Capture resolved-document state for replayable audit.
    doc_hash = hashlib.sha256(
        json.dumps(
            {k: v.__dict__ for k, v in sorted(subject_doc.methods.items())},
            sort_keys=True,
        ).encode()
    ).hexdigest()
    decision_log["resolved_doc_hash"] = doc_hash
    decision_log["doc_version"] = subject_doc.version
    decision_log["bound_method_id"] = cred.bound_method_id

    return True


# --- Reproduction of the failure trace ---
if __name__ == "__main__":
    issuer = DidDocument(did="did:example:orgA", methods={
        "did:example:orgA#issuer-1": VerificationMethod("did:example:orgA#issuer-1", "pkA")
    })
    # T0: subject doc has #key-1
    subject = DidDocument(did="did:example:agent-7", methods={
        "did:example:agent-7#key-1": VerificationMethod("did:example:agent-7#key-1", "pk1")
    })
    cred = Credential(
        issuer_did="did:example:orgA",
        subject_did="did:example:agent-7",
        bound_method_id="did:example:agent-7#key-1",
        scope=["submit:rfq"],
        signature="sig",
    )

    log = {}
    assert verify_and_authorize(cred, "did:example:agent-7#key-1", subject, issuer, log)

    # T1: rotation removes #key-1, adds #key-2
    subject.methods.pop("did:example:agent-7#key-1")
    subject.methods["did:example:agent-7#key-2"] = VerificationMethod(
        "did:example:agent-7#key-2", "pk2"
    )
    subject.version = 1

    # T2: new instance holding #key-2 presents the same credential.
    try:
        verify_and_authorize(cred, "did:example:agent-7#key-2", subject.resolve(), issuer, {})
        raise AssertionError("expected binding failure")
    except DidBindingError as e:
        print(f"GUARDRAIL FIRED: {e}")
