# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-its-aaif-did-mid-session-and-the-warrant-chain-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-its-aaif-did-mid-session-and-the-warrant-chain-forks.warrant.json
# Markdown SHA-256:   a3c7acb4b18836f9acfb869eaf806a2649e855857b3994d0103b8c475875eee3
# Code AST SHA-256:   b6368adb14089cefea7b365c4c285374ece00fdb297be0ca2acad508ff9b1a3a
# Verified Classes:   WarrantForkError, Warrant, Attestation, DIDRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

# warrant_fork.py — guard against mid-session AAIF re-attestation forks.
# Enforces: attestations pin their warrant; supersession is explicit and
# time-bounded; a verifier must not resolve by DID-document-latest.

from dataclasses import dataclass, field
from typing import Dict, List, Optional
import hashlib, time


class WarrantForkError(RuntimeError):
    """Raised when a DID has overlapping live warrants without explicit supersession,
    or when an attestation cannot be resolved against its pinned warrant version."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_hash: str
    issuer: str
    subject: str
    scope: frozenset
    not_before: float
    not_after: float
    did_doc_version: int
    supersedes: Optional[str] = None          # hash of the warrant this replaces
    effective_at: Optional[float] = None      # when supersession takes effect


@dataclass(frozen=True)
class Attestation:
    subject: str
    warrant_hash: str                          # MUST be pinned
    did_doc_version: int                       # MUST be pinned
    action: str
    timestamp: float


@dataclass
class DIDRegistry:
    # subject -> list of warrants, in issuance order
    chains: Dict[str, List[Warrant]] = field(default_factory=dict)

    def issue(self, w: Warrant) -> None:
        existing = self.chains.get(w.subject, [])
        # Fork guard: a new warrant from the same issuer may only coexist with
        # an older one if it explicitly supersedes it.
        for old in existing:
            if old.issuer != w.issuer:
                continue
            if old.not_after <= w.not_before:
                continue  # no temporal overlap, fine
            if w.supersedes != old.warrant_hash:
                raise WarrantForkError(
                    f"issuing {w.warrant_hash} for {w.subject} overlaps live "
                    f"warrant {old.warrant_hash} without supersedes edge"
                )
        self.chains.setdefault(w.subject, []).append(w)

    def resolve_pinned(self, warrant_hash: str, did_doc_version: int) -> Warrant:
        for ws in self.chains.values():
            for w in ws:
                if w.warrant_hash == warrant_hash:
                    if w.did_doc_version != did_doc_version:
                        raise WarrantForkError(
                            f"attestation pins {warrant_hash} at did_doc_version "
                            f"{did_doc_version}, but warrant was issued at "
                            f"{w.did_doc_version}; refusing latest-version fallback"
                        )
                    return w
        raise WarrantForkError(f"pinned warrant {warrant_hash} not found")


def verify_attestation(reg: DIDRegistry, att: Attestation, now: float) -> bool:
    w = reg.resolve_pinned(att.warrant_hash, att.did_doc_version)

    # Time validity is checked at the attestation's own timestamp, not `now`,
    # so a supersession that lands after the action does not retroactively
    # invalidate pinned in-flight work.
    if not (w.not_before <= att.timestamp <= w.not_after):
        raise WarrantForkError(
            f"attestation at {att.timestamp} outside warrant window "
            f"[{w.not_before}, {w.not_after}]"
        )

    # If a supersession exists, it must not have effective_at before the action.
    for other in reg.chains.get(w.subject, []):
        if other.supersedes == w.warrant_hash and other.effective_at is not None:
            if att.timestamp >= other.effective_at:
                raise WarrantForkError(
                    f"warrant {w.warrant_hash} superseded at {other.effective_at} "
                    f"by {other.warrant_hash}; attestation at {att.timestamp} "
                    f"post-dates supersession"
                )

    if att.action not in w.scope:
        raise WarrantForkError(
            f"action {att.action!r} not in pinned scope {sorted(w.scope)}"
        )
    return True
