# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-subtask-whose-sla-clock-was-started-by-the-delegator-before-the-contract-hash-was-sealed.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-subtask-whose-sla-clock-was-started-by-the-delegator-before-the-contract-hash-was-sealed.warrant.json
# Markdown SHA-256:   93f092b9e9b3abb8ad2167b1d11db46a5e69a2b95641dd0a5928d06ec3dc50e5
# Code AST SHA-256:   c7dc871c346ff87dd6ebb80d7f15c4a6478e2b4d5e11ccef1bb548e6ffd00ab0
# Verified Classes:   SLAEpochMismatchError, DelegationEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SLAEpochMismatchError(RuntimeError):
    """Raised when a delegation envelope's SLA clock epoch cannot be attested."""
    pass


@dataclass
class DelegationEnvelope:
    scope: str
    sla_duration_s: int
    sla_deadline_ts: int          # delegator-asserted absolute deadline
    seal_timestamp_ts: int | None # None if delegator did not hash the seal time
    contract_hash: str
    clock_skew_tolerance_s: int = 2


def _recompute_hash(env: DelegationEnvelope) -> str:
    payload = {
        "scope": env.scope,
        "sla_duration_s": env.sla_duration_s,
        "seal_timestamp_ts": env.seal_timestamp_ts,
    }
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


def accept_delegation(
    env: DelegationEnvelope,
    receipt_timestamp_ts: int,
    min_viable_budget_s: int,
) -> int:
    """Return remaining budget in seconds, or raise SLAEpochMismatchError.

    Refuses when the SLA clock epoch cannot be independently recomputed
    from sealed fields, because such a commitment is not replay-adjudicable.
    """
    if env.seal_timestamp_ts is None:
        raise SLAEpochMismatchError(
            "envelope carries no seal_timestamp; SLA deadline is an unverifiable "
            "delegator assertion and cannot be enforced in dispute replay"
        )

    if _recompute_hash(env) != env.contract_hash:
        raise SLAEpochMismatchError(
            "contract_hash does not cover seal_timestamp; the seal time was "
            "appended after hashing and is therefore not attested"
        )

    recomputed_deadline = env.seal_timestamp_ts + env.sla_duration_s
    drift = abs(recomputed_deadline - env.sla_deadline_ts)
    if drift > env.clock_skew_tolerance_s:
        raise SLAEpochMismatchError(
            f"transmitted sla_deadline ({env.sla_deadline_ts}) disagrees with "
            f"seal-anchored deadline ({recomputed_deadline}) by {drift}s; "
            "delegator computed the clock from a different epoch than it sealed"
        )

    remaining = env.sla_deadline_ts - receipt_timestamp_ts
    if remaining < min_viable_budget_s:
        raise SLAEpochMismatchError(
            f"remaining budget {remaining}s below declared minimum "
            f"{min_viable_budget_s}s after epoch reconciliation; "
            "refuse and counter-offer a fresh seal"
        )

    return remaining
