# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-escrow-release-when-a-capability-contract-s-sla-clock-and-the-escrow-s-dispute-window-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-escrow-release-when-a-capability-contract-s-sla-clock-and-the-escrow-s-dispute-window-disagree.warrant.json
# Markdown SHA-256:   59797c94c3efc7cca9febfda8d8d05ba1c0be670797112f9803ec9ab572ab952
# Code AST SHA-256:   48ba5b11c15fd83a2155f9229c5432bb5341ab165da3b5932c0175b040c41444
# Verified Classes:   EscrowReleaseRefused, CapabilityContract, Escrow, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class EscrowReleaseRefused(RuntimeError):
    """Raised when a completion attestation cannot be settled against the escrow."""


@dataclass(frozen=True)
class CapabilityContract:
    contract_id: str
    sla_deadline: datetime
    breach_clause_reallocative: bool  # True => breach moves value to consumer


@dataclass(frozen=True)
class Escrow:
    escrow_id: str
    funded_at: datetime
    dispute_window: timedelta
    held: bool = False


@dataclass(frozen=True)
class Attestation:
    contract_id: str
    completed_at: datetime
    signature_valid: bool


def settle_escrow(escrow: Escrow, contract: CapabilityContract,
                  attestation: Attestation, now: datetime) -> str:
    if attestation.contract_id != contract.contract_id:
        raise EscrowReleaseRefused(
            f"attestation for {attestation.contract_id!r} does not match "
            f"contract {contract.contract_id!r}"
        )
    if not attestation.signature_valid:
        raise EscrowReleaseRefused("attestation signature invalid; refusing release")

    window_close = escrow.funded_at + escrow.dispute_window
    sla_breached = attestation.completed_at > contract.sla_deadline

    # The non-obvious boundary: a valid attestation that violates a reallocative
    # SLA clause must be held even while the dispute window is still open.
    if sla_breached and contract.breach_clause_reallocative:
        raise EscrowReleaseRefused(
            f"completion at {attestation.completed_at.isoformat()} exceeds SLA "
            f"deadline {contract.sla_deadline.isoformat()} under a reallocative "
            f"breach clause; escrow {escrow.escrow_id!r} must be held for "
            f"consumer reconciliation (dispute window closes "
            f"{window_close.isoformat()}, but window is not an SLA proxy)"
        )

    if now >= window_close and not escrow.held:
        raise EscrowReleaseRefused(
            f"dispute window closed at {window_close.isoformat()} with no "
            f"settlement; escrow {escrow.escrow_id!r} requires manual resolution"
        )

    return "RELEASED_TO_PROVIDER"
