# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-delegated-authority-survive-credential-rotation-but-its-audit-chain-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-delegated-authority-survive-credential-rotation-but-its-audit-chain-does-not.warrant.json
# Markdown SHA-256:   ae273e840b60d1d28f39fa5ef1e769848eb531c265e77f385003ccd1123fa7fc
# Code AST SHA-256:   e40c3293f11a8b0ff6a1c8dcfbec66c1c288175fc6f54e557ce74fef0f5fff0c
# Verified Classes:   RotationAttestationError, AuditAttributionError, KeyStatus, AuditRecord, DIDDocument
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class RotationAttestationError(RuntimeError):
    """Raised when a key is retired without a committed, dual-signed rotation attestation."""


class AuditAttributionError(RuntimeError):
    """Raised when an audit record cannot be attributed to a DID at replay time."""


@dataclass
class KeyStatus:
    key_id: str
    status: str  # "active" | "retired" | "revoked"
    rotation_attestation: Optional[dict] = None
    retired_at: Optional[float] = None


@dataclass
class AuditRecord:
    actor_did: str
    signed_by: str
    signed_at: float
    action_hash: str


@dataclass
class DIDDocument:
    did: str
    keys: dict = field(default_factory=dict)  # key_id -> KeyStatus

    def rotate(self, old_key: str, new_key: str, attestation: dict) -> None:
        """
        Two-phase rotation: attestation MUST be committed before the old key
        transitions to 'retired'. This is the guardrail that prevents the
        retroactive-attestation failure.
        """
        if old_key not in self.keys or self.keys[old_key].status != "active":
            raise RotationAttestationError(
                f"cannot rotate {old_key}: not active on {self.did}"
            )
        # Phase 1: verify the attestation is dual-signed and commits to new_key.
        if attestation.get("from") != old_key or attestation.get("to") != new_key:
            raise RotationAttestationError(
                f"attestation does not link {old_key} -> {new_key}"
            )
        if not attestation.get("signed_by_both"):
            raise RotationAttestationError(
                "rotation attestation must be signed by both old and new keys"
            )
        # Phase 2: only now flip status, atomically with the attestation.
        self.keys[old_key] = KeyStatus(
            key_id=old_key,
            status="retired",
            rotation_attestation=attestation,
            retired_at=attestation["effective_at"],
        )
        self.keys[new_key] = KeyStatus(key_id=new_key, status="active")


def replay_attribution(doc: DIDDocument, records: list[AuditRecord]) -> dict:
    """
    Replay an audit log against the current DID document. Returns
    {attributed: [...], quarantined: [...]}. Raises AuditAttributionError
    only if a record's key is *revoked* (a hard failure); 'retired' without
    attestation is quarantined, not failed.
    """
    attributed, quarantined = [], []
    for r in records:
        ks = doc.keys.get(r.signed_by)
        if ks is None:
            raise AuditAttributionError(
                f"key {r.signed_by} unknown on {doc.did}; cannot attribute {r.action_hash}"
            )
        if ks.status == "revoked" and (ks.retired_at or 0) <= r.signed_at:
            raise AuditAttributionError(
                f"key {r.signed_by} was revoked before {r.action_hash} was signed"
            )
        if ks.status == "retired":
            if ks.rotation_attestation is None:
                # The boundary failure: retired without a forward-link.
                quarantined.append(r)
                continue
            if r.signed_at > ks.rotation_attestation["effective_at"]:
                # Record post-dates the cutover but was signed by the old key:
                # this is a real violation, not a rotation artifact.
                raise AuditAttributionError(
                    f"record {r.action_hash} signed by {r.signed_by} after its retirement"
                )
        attributed.append(r)
    return {"attributed": attributed, "quarantined": quarantined}


# --- Demonstration of the boundary failure ---
if __name__ == "__main__":
    doc = DIDDocument(did="did:aaif:O", keys={"k1": KeyStatus("k1", "active")})
    records = [AuditRecord("did:aaif:W3", "k1", time.time() - 3600, f"h{i}") for i in range(3)]

    # Correct path: dual-signed attestation commits before retirement.
    good_att = {"from": "k1", "to": "k2", "effective_at": time.time(),
                "reason": "scheduled", "signed_by_both": True}
    doc.rotate("k1", "k2", good_att)
    result = replay_attribution(doc, records)
    assert len(result["attributed"]) == 3 and not result["quarantined"]

    # Failure path: retirement without attestation -> quarantine, not silent pass.
    doc2 = DIDDocument(did="did:aaif:P", keys={"k1": KeyStatus("k1", "active")})
    doc2.keys["k1"] = KeyStatus("k1", "retired", rotation_attestation=None)
    result2 = replay_attribution(doc2, records)
    if result2["quarantined"]:
        raise RotationAttestationError(
            f"{len(result2['quarantined'])} records quarantined: key retired "
            "without a committed rotation attestation (audit chain discontinuous)"
        )
