# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-verifiable-credential-across-an-aaif-chain-and-the-resolver-clock-skew-invalidates-the-parent-link-mid-ha.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-verifiable-credential-across-an-aaif-chain-and-the-resolver-clock-skew-invalidates-the-parent-link-mid-ha.warrant.json
# Markdown SHA-256:   727eaf34513b02cdce2d5d944c2eddc69fbf232d328abd11236490830ec812bc
# Code AST SHA-256:   a9ccfdea0a2b69dfe665f3a2fd40111ebd479c76cf86d465a7533e19f72e9b73
# Verified Classes:   DelegationExpired, VerificationMethodUnresolvable, ChainLink, DIDDocument
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class DelegationExpired(RuntimeError):
    """Raised when a re-delegation or verification crosses the temporal boundary."""
    pass


class VerificationMethodUnresolvable(RuntimeError):
    """Raised when a rotated-out verification method is no longer in the DID document."""
    pass


@dataclass
class ChainLink:
    issuer_did: str
    subject_did: str
    valid_from: float
    valid_until: float
    verification_method_id: str
    scope: frozenset


@dataclass
class DIDDocument:
    did: str
    # verification_method_id -> public key bytes (historical methods retained)
    methods: dict = field(default_factory=dict)
    # methods rotated out but still resolvable within maxChainLifetime
    historical_methods: dict = field(default_factory=dict)

    def resolve(self, method_id: str) -> Optional[bytes]:
        return self.methods.get(method_id) or self.historical_methods.get(method_id)


CLOCK_SKEW_BUDGET = 60.0          # seconds
HANDOFF_MARGIN = 120.0            # delegator refuses below this
MAX_CHAIN_LIFETIME = 3600.0       # resolver must retain rotated keys this long


def re_delegate(
    parent: ChainLink,
    delegator_did: str,
    delegate_did: str,
    narrowed_scope: frozenset,
    now: float,
    requested_ttl: float = 600.0,
) -> ChainLink:
    """Delegator-side guard: refuse to sign a child that outlives its parent."""
    if not narrowed_scope.issubset(parent.scope):
        raise DelegationExpired(
            f"scope widening refused: {narrowed_scope} not subset of {parent.scope}"
        )
    remaining = parent.valid_until - now
    if remaining < HANDOFF_MARGIN:
        raise DelegationExpired(
            f"refusing re-delegation from {delegator_did}: parent {parent.issuer_did} "
            f"expires in {remaining:.1f}s < handoff margin {HANDOFF_MARGIN}s"
        )
    child_until = min(parent.valid_until, now + requested_ttl)
    return ChainLink(
        issuer_did=delegator_did,
        subject_did=delegate_did,
        valid_from=now,
        valid_until=child_until,
        verification_method_id=f"{delegator_did}#key-1",
        scope=narrowed_scope,
    )


def verify_chain(
    chain: list,
    documents: dict,
    now: float,
) -> None:
    """Delegate-side guard: evaluate against the weakest link, with skew budget."""
    if not chain:
        raise DelegationExpired("empty chain")
    effective_until = min(link.valid_until for link in chain) - CLOCK_SKEW_BUDGET
    if now > effective_until:
        weakest = min(chain, key=lambda l: l.valid_until)
        raise DelegationExpired(
            f"chain invalid at t={now:.1f}: weakest link {weakest.issuer_did} "
            f"expired at {weakest.valid_until:.1f} (effective {effective_until:.1f})"
        )
    for link in chain:
        doc = documents.get(link.issuer_did)
        if doc is None or doc.resolve(link.verification_method_id) is None:
            raise VerificationMethodUnresolvable(
                f"cannot resolve {link.verification_method_id} for {link.issuer_did}; "
                f"rotated methods must be retained for {MAX_CHAIN_LIFETIME}s"
            )


if __name__ == "__main__":
    t0 = time.time()
    root = ChainLink(
        issuer_did="did:aaif:root",
        subject_did="did:aaif:planner",
        valid_from=t0,
        valid_until=t0 + 3600.0,
        verification_method_id="did:aaif:root#key-1",
        scope=frozenset({"tool:write:staging"}),
    )
    # Planner re-delegates ten seconds before parent expiry: must refuse.
    try:
        re_delegate(
            parent=root,
            delegator_did="did:aaif:planner",
            delegate_did="did:aaif:executor",
            narrowed_scope=frozenset({"tool:write:staging:table_x"}),
            now=t0 + 3590.0,
        )
    except DelegationExpired as e:
        print(f"delegator refused: {e}")

    # Simulate the split-brain: parent expired, stale cache saw it as valid.
    docs = {
        "did:aaif:root": DIDDocument(
            did="did:aaif:root",
            methods={"did:aaif:root#key-2": b"rotated"},
            historical_methods={"did:aaif:root#key-1": b"old"},
        )
    }
    try:
        verify_chain([root], docs, now=t0 + 3605.0)
    except DelegationExpired as e:
        print(f"executor refused: {e}")
