# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-aaif-credential-whose-scope-chain-is-valid-but-whose-attenuation-interval-excludes-the-current-invocation-win.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-delegated-aaif-credential-whose-scope-chain-is-valid-but-whose-attenuation-interval-excludes-the-current-invocation-win.warrant.json
# Markdown SHA-256:   5b6ac5e552922c6cefae8c0c7a105ee19e00b23f28d214e442fd555479b52796
# Code AST SHA-256:   7b207663447a9c179a92cff7cb66f99fa3694a65f936c721ee21bc65ba513000
# Verified Classes:   DelegationIntervalError, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Sequence


class DelegationIntervalError(RuntimeError):
    """Raised when a delegated AAIF credential chain's interval intersection
    does not contain the invocation timestamp, or when the chain is malformed."""
    pass


@dataclass(frozen=True)
class Hop:
    agent_id: str
    nbf: float
    exp: float
    parent_ref: str | None


def verify_chain_interval(chain: Sequence[Hop], now: float | None = None) -> float:
    """Return the intersection expiry for a fully-resolved AAIF chain.

    Enforces: (1) chain completeness, (2) single shared `now`, (3) monotonic
    attenuation (child interval contained in parent interval).
    """
    if not chain:
        raise DelegationIntervalError("empty AAIF chain: nothing to verify")

    if now is None:
        now = time.time()

    # Condition 3: monotonic attenuation, root -> leaf.
    for parent, child in zip(chain, chain[1:]):
        if child.nbf < parent.nbf or child.exp > parent.exp:
            raise DelegationIntervalError(
                f"non-monotonic attenuation: hop {child.agent_id} "
                f"[{child.nbf},{child.exp}] not contained in parent "
                f"{parent.agent_id} [{parent.nbf},{parent.exp}]"
            )

    # Condition 1: chain completeness — the last hop must be a leaf.
    if chain[-1].parent_ref is not None:
        raise DelegationIntervalError(
            f"incomplete chain: leaf {chain[-1].agent_id} still references "
            f"parent {chain[-1].parent_ref}; resolve before verifying"
        )

    # Condition 2: single shared `now` across the whole intersection.
    lo = max(h.nbf for h in chain)
    hi = min(h.exp for h in chain)

    if now < lo:
        raise DelegationIntervalError(
            f"deferred: invocation at {now} precedes intersection start {lo}"
        )
    if now >= hi:
        # Identify the hop that killed the intersection, for the audit log.
        binding = min(chain, key=lambda h: h.exp)
        raise DelegationIntervalError(
            f"interval-intersection failure: now={now} >= intersection exp={hi}; "
            f"binding hop = {binding.agent_id} (leaf exp was "
            f"{chain[-1].exp}, which is not the governing interval)"
        )

    return hi


def invoke_with_chain(chain: Sequence[Hop], tool_call) -> object:
    """Resume-safe invocation: re-intersects on every call, never trusts a
    cached leaf `exp`. This is the guardrail the observed worker lacked."""
    try:
        expiry = verify_chain_interval(chain)
    except DelegationIntervalError:
        # Do not swallow: surface to the scheduler so the task can be
        # re-delegated under a fresh chain rather than silently proceeding.
        raise
    return tool_call(expiry)
