# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-warrant-after-the-parent-scope-narrows-stale-warrant-amplification-in-aaif-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-warrant-after-the-parent-scope-narrows-stale-warrant-amplification-in-aaif-delegation-chains.warrant.json
# Markdown SHA-256:   79d82695107b9d380a4dd8ad8ad128efa5b15601f77fa4198144aae2fac90e94
# Code AST SHA-256:   5d8d5d8ce9f11ac5cb74bea872f78b3a175dc98d9ad8c6580e9842a090cff247
# Verified Classes:   StaleWarrantError, Warrant, WarrantRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a re-signed warrant's derivation lineage is no longer live."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer_key: str
    scope: frozenset
    parent_id: str | None
    parent_version: int | None
    signed_at: float
    ttl: float

    def is_expired(self, now: float) -> bool:
        return now > self.signed_at + self.ttl


class WarrantRegistry:
    """Tracks warrant versions and supersession. Answers lineage-liveness queries."""

    def __init__(self) -> None:
        self._versions: dict[str, list[dict]] = {}

    def publish(self, warrant_id: str, version: int, scope: frozenset, superseded: bool = False) -> None:
        self._versions.setdefault(warrant_id, []).append(
            {"version": version, "scope": scope, "superseded": superseded}
        )

    def supersede(self, warrant_id: str, version: int) -> None:
        for rec in self._versions.get(warrant_id, []):
            if rec["version"] == version:
                rec["superseded"] = True

    def current_scope(self, warrant_id: str) -> frozenset | None:
        recs = self._versions.get(warrant_id)
        if not recs:
            return None
        live = [r for r in recs if not r["superseded"]]
        return live[-1]["scope"] if live else None

    def derivation_is_live(self, parent_id: str, parent_version: int) -> bool:
        for rec in self._versions.get(parent_id, []):
            if rec["version"] == parent_version:
                return not rec["superseded"]
        return False


def verify_re_signed(
    child: Warrant,
    registry: WarrantRegistry,
    now: float,
    max_lineage_staleness_s: float = 60.0,
) -> None:
    """
    Verify a re-signed (derived) warrant. Signatures are assumed pre-checked.
    This enforces the lineage-freshness invariant that signature checks miss.
    """
    if child.parent_id is None or child.parent_version is None:
        raise StaleWarrantError(
            f"warrant {child.warrant_id} is re-signed but carries no parent_id/parent_version; "
            "derivation lineage is unverifiable and attenuation cannot propagate"
        )

    if child.is_expired(now):
        raise StaleWarrantError(f"warrant {child.warrant_id} expired at {child.signed_at + child.ttl}")

    if not registry.derivation_is_live(child.parent_id, child.parent_version):
        raise StaleWarrantError(
            f"warrant {child.warrant_id} derives from {child.parent_id} v{child.parent_version}, "
            "which is superseded or revoked; re-signing froze a scope the parent no longer holds"
        )

    current_parent_scope = registry.current_scope(child.parent_id)
    if current_parent_scope is None:
        raise StaleWarrantError(
            f"warrant {child.warrant_id} derives from {child.parent_id}, which has no live version"
        )

    if not child.scope.issubset(current_parent_scope):
        leaked = child.scope - current_parent_scope
        raise StaleWarrantError(
            f"warrant {child.warrant_id} claims {sorted(leaked)} not present in current parent scope; "
            "stale-warrant amplification"
        )


def issue_derived_warrant(
    parent: Warrant,
    child_id: str,
    child_scope: frozenset,
    issuer_key: str,
    registry: WarrantRegistry,
) -> Warrant:
    """Mint a re-signed warrant, recording the parent version it was derived from."""
    if not child_scope.issubset(parent.scope):
        raise StaleWarrantError(
            f"child scope {sorted(child_scope)} not a subset of parent {sorted(parent.scope)}"
        )
    parent_version = registry._versions[parent.warrant_id][-1]["version"]
    return Warrant(
        warrant_id=child_id,
        issuer_key=issuer_key,
        scope=child_scope,
        parent_id=parent.warrant_id,
        parent_version=parent_version,
        signed_at=time.time(),
        ttl=parent.ttl,
    )
