# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-verifiable-credential-chain-when-its-did-document-is-served-by-a-resolver-whose-cache-has-diverged-from-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-verifiable-credential-chain-when-its-did-document-is-served-by-a-resolver-whose-cache-has-diverged-from-th.warrant.json
# Markdown SHA-256:   13153a6bbe49ac926c195a01139ebd781fae41bd63d489313ec1bfef931126eb
# Code AST SHA-256:   e55c9d9f36ca03684ed3f0c9fbadd8c018c44f5f88c8b351c377e6937dd3e2a3
# Verified Classes:   EpochSplitError, DelegationValidator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EpochSplitError(RuntimeError):
    """Raised when DID document state and revocation state cannot be shown
    to belong to the same epoch, making a delegation chain unverifiable."""


class DelegationValidator:
    def __init__(self, resolver, registry, max_staleness_s: float = 30.0):
        self.resolver = resolver
        self.registry = registry
        self.max_staleness_s = max_staleness_s

    def validate(self, chain, decision_time):
        # Full re-read of every component; partial refresh is the bug.
        dids = {hop.issuer_did: self.resolver.resolve(hop.issuer_did) for hop in chain}
        statuses = {hop.vc_id: self.registry.status(hop.vc_id) for hop in chain}

        epochs = {d.epoch_token for d in dids.values()}
        epochs |= {s.sequence for s in statuses.values()}
        if len(epochs) > 1:
            # Re-read once; if still split, fail closed.
            dids = {k: self.resolver.resolve(k) for k in dids}
            statuses = {k: self.registry.status(k) for k in statuses}
            epochs = {d.epoch_token for d in dids.values()} | {s.sequence for s in statuses.values()}
            if len(epochs) > 1:
                raise EpochSplitError(
                    f"epochs diverge across reads: {sorted(epochs)}; "
                    f"cannot establish co-validity for chain {[h.vc_id for h in chain]}"
                )

        for hop in chain:
            st = statuses[hop.vc_id]
            if decision_time - st.fetched_at > self.max_staleness_s:
                raise EpochSplitError(
                    f"status for {hop.vc_id} is {decision_time - st.fetched_at:.1f}s stale, "
                    f"exceeds grace window {self.max_staleness_s}s"
                )
            if st.revoked:
                return False
            doc = dids[hop.issuer_did]
            if not doc.has_method(hop.signing_key_id, at=hop.issued_at):
                # Key absent at issuance time => chain is forged or pre-dates the key.
                return False
            if doc.method_retired(hop.signing_key_id, before=hop.valid_until):
                return False

        for parent, child in zip(chain, chain[1:]):
            if not is_scope_subset(child.scope, parent.scope):
                raise EpochSplitError(
                    f"scope {child.scope!r} not contained in parent {parent.scope!r}"
                )
        return True
