# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-renew-an-a2a-sla-when-the-counterparty-s-execution-receipt-chain-has-a-valid-root-but-a-broken-interi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-renew-an-a2a-sla-when-the-counterparty-s-execution-receipt-chain-has-a-valid-root-but-a-broken-interi.warrant.json
# Markdown SHA-256:   38493a13249cd9f02ee3ac88c2200ae079319ce03c04a61eab61bb63d6cf4556
# Code AST SHA-256:   448ad45c7cf7dbac6fb7900fa0fe6de93e5b0adc480898c30ff21a16927590f7
# Verified Classes:   ReceiptChainForkError, Receipt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReceiptChainForkError(RuntimeError):
    """Raised when a root verifies but an interior link in the receipt chain does not."""


@dataclass(frozen=True)
class Receipt:
    step_id: int
    output_hash: str
    prev_receipt_hash: str
    sig: str


def _h(r: Receipt) -> str:
    return hashlib.sha256(
        f"{r.step_id}:{r.output_hash}:{r.prev_receipt_hash}".encode()
    ).hexdigest()


def verify_and_renew(
    observed: list[Receipt],
    committed_root: str,
    root_signature_valid: bool,
    provider_attests_no_reemit: bool,
) -> bool:
    if not root_signature_valid:
        # Ordinary invalid-receipt case: lapse, do not escalate.
        return False

    # Recompute the Merkle root over the consumer-observed chain.
    local_root = observed[-1].prev_receipt_hash if observed else ""
    if local_root != committed_root and not provider_attests_no_reemit:
        raise ReceiptChainForkError(
            f"committed_root={committed_root!r} != local_root={local_root!r}; "
            "provider history diverged from consumer observation"
        )

    # Full-chain interior link check. This is the invariant that root-only
    # validation skips.
    for prev, cur in zip(observed, observed[1:]):
        if _h(prev) != cur.prev_receipt_hash:
            raise ReceiptChainForkError(
                f"interior link broken between step {prev.step_id} and "
                f"{cur.step_id}: expected prev_receipt_hash={_h(prev)!r}, "
                f"got {cur.prev_receipt_hash!r}"
            )

    return True


def renew_sla(observed: list[Receipt], committed_root: str,
              root_signature_valid: bool,
              provider_attests_no_reemit: bool) -> str:
    try:
        ok = verify_and_renew(
            observed, committed_root, root_signature_valid,
            provider_attests_no_reemit,
        )
    except ReceiptChainForkError as e:
        return f"REFUSE_AND_ESCALATE: {e}"
    return "RENEW" if ok else "REFUSE_AND_LAPSE"
