# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-delegated-consent-chain-whose-intermediate-hop-has-been-garbage-collected.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-delegated-consent-chain-whose-intermediate-hop-has-been-garbage-collected.warrant.json
# Markdown SHA-256:   81650ed1e89b5124ded6ba209f587a2517a2958b6deeb5178796b5ea7f2438e8
# Code AST SHA-256:   54ae5ff4cd53b2aa716be235812f5339a21c59b632eee748cbda76407534c371
# Verified Classes:   AttenuationUnprovableError, Link
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttenuationUnprovableError(RuntimeError):
    """Raised when a chain verifies cryptographically but its terminal
    capability cannot be shown to be a monotone attenuation of every
    surviving ancestor grant, because an interior consent record is missing."""
    pass


@dataclass
class Link:
    issuer: str
    subject: str
    scopes: frozenset
    constraints: dict            # e.g. {"max_rows": 1000}
    signature_valid: bool
    consent_record: Optional[dict] = None   # None => ledger miss / GC'd hop


def _narrower(terminal_scopes, terminal_constraints, ancestor: Link) -> bool:
    """True iff terminal is a legitimate attenuation of `ancestor`:
    scopes are a subset, and every ancestor constraint is present and
    no looser in the terminal."""
    if not terminal_scopes <= ancestor.scopes:
        return False
    for k, v in ancestor.constraints.items():
        if k not in terminal_constraints:
            return False          # constraint dropped => widening
        if terminal_constraints[k] > v:
            return False          # constraint loosened => widening
    return True


def verify_chain(chain: list[Link]) -> dict:
    """Return the effective (scopes, constraints) for the terminal subject,
    or raise if attenuation cannot be proven."""
    for link in chain:
        if not link.signature_valid:
            raise AttenuationUnprovableError(
                f"link {link.issuer}->{link.subject} failed signature check"
            )

    terminal = chain[-1]
    survivors = [l for l in chain[:-1] if l.consent_record is not None]
    missing = [l for l in chain[:-1] if l.consent_record is None]

    if not survivors:
        raise AttenuationUnprovableError(
            "no surviving interior consent records; attenuation unprovable"
        )

    # Conservative narrowing: apply the tightest surviving constraint set.
    for anc in survivors:
        if not _narrower(terminal.scopes, terminal.constraints, anc):
            # Terminal contains a scope or drops a constraint not justified
            # by any surviving ancestor. The missing hop is load-bearing.
            raise AttenuationUnprovableError(
                f"terminal capability not derivable from surviving ancestor "
                f"{anc.issuer}; missing interior record(s) "
                f"{[l.subject for l in missing]} may have carried the "
                f"attenuation proof"
            )

    effective_constraints = dict(terminal.constraints)
    for anc in survivors:
        for k, v in anc.constraints.items():
            effective_constraints[k] = min(effective_constraints.get(k, v), v)

    return {
        "scopes": frozenset(terminal.scopes),
        "constraints": effective_constraints,
        "tolerated_missing_hops": [l.subject for l in missing],
    }
