# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-chain-whose-attenuation-proof-outlives-its-parent-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-chain-whose-attenuation-proof-outlives-its-parent-warrant.warrant.json
# Markdown SHA-256:   399962ca2ca6fcbb755ac19c7831ee9df2e91bdcc589d4e6efdebb05b65137ae
# Code AST SHA-256:   d8ec37bd94d3a8856b610485680566f0db5c7405890f7fd09305c1b871027cf1
# Verified Classes:   DelegatedChainLivenessError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class DelegatedChainLivenessError(RuntimeError):
    """Raised when a delegated AAIF warrant chain cannot be proven live
    against its ancestor lineage within the verifier's freshness window."""
    pass


def verify_delegated_chain(chain, crl, now, freshness_window_s):
    """
    chain: list of warrants, root-first. Each warrant has:
        id, parent_id, parent_hash, not_after, attenuation_proof
    crl:   dict warrant_id -> revoked_at (epoch seconds)
    Admission requires: local validity AND every ancestor live within
    freshness_window_s. Unresolvable or stale ancestors fail closed.
    """
    if not chain:
        raise DelegatedChainLivenessError("empty chain presented")

    # 1. Local validity: attenuation proofs and own TTL.
    for i, w in enumerate(chain):
        if w["not_after"] <= now:
            raise DelegatedChainLivenessError(
                f"warrant {w['id']} expired at {w['not_after']}"
            )
        if i > 0:
            parent = chain[i - 1]
            if w["parent_hash"] != parent["hash"]:
                raise DelegatedChainLivenessError(
                    f"warrant {w['id']} parent_hash does not match ancestor"
                )
            if not verify_attenuation(w["attenuation_proof"], parent, w):
                raise DelegatedChainLivenessError(
                    f"warrant {w['id']} attenuation proof invalid"
                )

    # 2. Lineage liveness: walk every ancestor, not just the leaf.
    for w in chain:
        wid = w.get("id")
        if wid is None:
            # Hash-only reference: cannot be CRL-addressable. Fail closed.
            raise DelegatedChainLivenessError(
                f"ancestor {w.get('parent_hash')} has no resolvable id; "
                "unrevokable chain must not be admitted"
            )
        revoked_at = crl.get(wid)
        if revoked_at is not None and revoked_at <= now:
            raise DelegatedChainLivenessError(
                f"ancestor {wid} revoked at {revoked_at}; leaf admission denied"
            )

    # 3. Freshness: the CRL snapshot must be recent enough that an
    # ancestor revoked since the snapshot cannot slip through.
    snapshot_age = now - crl.get("__snapshot_at", 0)
    if snapshot_age > freshness_window_s:
        raise DelegatedChainLivenessError(
            f"CRL snapshot age {snapshot_age}s exceeds freshness window "
            f"{freshness_window_s}s; lineage liveness unproven"
        )

    return True


def verify_attenuation(proof, parent, child):
    # Placeholder for the AAIF signature fold; returns bool.
    return proof is not None and proof.get("valid", False)
