# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-anchor-a-federated-peer-s-did-before-honoring-a-delegated-warrant-and-why-signature-validity-alone-is-insufficie.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-anchor-a-federated-peer-s-did-before-honoring-a-delegated-warrant-and-why-signature-validity-alone-is-insufficie.warrant.json
# Markdown SHA-256:   80799ba596fa6b52109b13a9eef9319e2510a6d17acb5c20b2c88ed031460b38
# Code AST SHA-256:   5e9f28e62e91b1c94c0dfb738dbb524b1d6e615b570955e69762b6134c29f4e7
# Verified Classes:   AnchorEpochViolation, DidDocument, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AnchorEpochViolation(RuntimeError):
    """Raised when a warrant's issuance anchor epoch is incompatible with the
    peer's current DID document in a way that signature verification cannot catch."""


@dataclass(frozen=True)
class DidDocument:
    did: str
    controller: str
    verification_methods: tuple[str, ...]
    updated: str

    def epoch_hash(self) -> str:
        canonical = json.dumps(
            {
                "did": self.did,
                "controller": self.controller,
                "vm": sorted(self.verification_methods),
                "updated": self.updated,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass(frozen=True)
class Warrant:
    issuer: str            # DID string, e.g. did:web:org-b
    subject: str
    did_epoch: str         # epoch hash captured at issuance
    issuer_controller: str # controller in force at issuance
    signature_valid: bool


def admit_warrant(warrant: Warrant, live_doc: DidDocument) -> bool:
    """Fail-closed admission for a federated warrant.

    Three-way equality required: issuance controller == live controller ==
    the controller the consumer trusts. Signature validity is necessary but
    never sufficient across an anchor-epoch boundary.
    """
    if warrant.issuer != live_doc.did:
        raise AnchorEpochViolation(
            f"warrant issuer {warrant.issuer} != resolved DID {live_doc.did}"
        )

    epoch_changed = warrant.did_epoch != live_doc.epoch_hash()
    controller_changed = warrant.issuer_controller != live_doc.controller

    if not epoch_changed:
        if not warrant.signature_valid:
            raise AnchorEpochViolation(
                f"epoch stable but signature invalid for {warrant.issuer}"
            )
        return True

    # Epoch changed: classify rotation vs. re-anchoring.
    if controller_changed:
        # Re-anchoring: warrant was issued by a controller that no longer
        # holds the DID. Must NOT be honored under any fallback.
        raise AnchorEpochViolation(
            "controller re-anchored: "
            f"issued by {warrant.issuer_controller}, now {live_doc.controller}; "
            f"epoch {warrant.did_epoch[:12]} -> {live_doc.epoch_hash()[:12]}; "
            "warrant must be re-issued by current controller"
        )

    # Rotation: same controller, new key material. Re-verify, then admit.
    if not warrant.signature_valid:
        raise AnchorEpochViolation(
            f"rotation under stable controller {live_doc.controller} but "
            "warrant does not verify against current key set"
        )
    return True


def consume(warrant: Warrant, resolver) -> bool:
    live = resolver(warrant.issuer)
    if live is None:
        raise AnchorEpochViolation(f"could not resolve {warrant.issuer}")
    return admit_warrant(warrant, live)
