# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-attribute-tokens-to-a-sub-task-it-cannot-prove-it-caused.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-attribute-tokens-to-a-sub-task-it-cannot-prove-it-caused.warrant.json
# Markdown SHA-256:   8d4312cd1aabda47b9d2c2faa3afa580d5a69bf900583ceb40721cd2c1c5cbfe
# Code AST SHA-256:   b3f29f422404db82daf5888a8dcb90c900fe4c9e0d5a00703f03fe3dd302d2df
# Verified Classes:   AttributionWitnessError, InvocationMeter
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class AttributionWitnessError(RuntimeError):
    """Raised when a token attribution cannot be backed by a replayable witness."""


@dataclass(frozen=True)
class InvocationMeter:
    sub_task_id: str
    prompt_tokens: int
    completion_tokens: int
    cache_read_tokens: int
    segment_manifest_hash: Optional[str]  # hash of labeled prompt segments
    predecessor_ledger_hash: Optional[str]  # set on resume/handoff
    is_replay: bool = False


def attribute_tokens(meter: InvocationMeter, known_predecessor: Optional[str]) -> dict:
    """
    Return a point attribution ONLY if a replayable witness exists.
    Otherwise raise, forcing the caller to emit UNKNOWN with an interval.
    """
    # Replay/audit work is a separate budget line, never production cost.
    if meter.is_replay:
        return {"bucket": "verification", "tokens": meter.prompt_tokens + meter.completion_tokens}

    # Condition 1: exclusive binding requires a segment manifest.
    if meter.segment_manifest_hash is None:
        raise AttributionWitnessError(
            f"sub_task={meter.sub_task_id}: no segment manifest; prompt may be a "
            f"multi-sub-task concatenation. Refusing point attribution."
        )

    # Condition 3: on resume, predecessor ledger must be present and match.
    if meter.predecessor_ledger_hash is not None:
        if known_predecessor is None:
            raise AttributionWitnessError(
                f"sub_task={meter.sub_task_id}: resumed invocation cites predecessor "
                f"{meter.predecessor_ledger_hash} but no such ledger is held locally; "
                f"handoff boundary unverifiable."
            )
        if meter.predecessor_ledger_hash != known_predecessor:
            raise AttributionWitnessError(
                f"sub_task={meter.sub_task_id}: predecessor ledger mismatch "
                f"({meter.predecessor_ledger_hash} != {known_predecessor}); "
                f"double-count risk across handoff."
            )

    # Condition 2: cache-read tokens are amortized, not charged to the sub-task.
    attributable = (meter.prompt_tokens - meter.cache_read_tokens) + meter.completion_tokens
    if attributable < 0:
        raise AttributionWitnessError(
            f"sub_task={meter.sub_task_id}: cache_read exceeds prompt; meter is corrupt."
        )

    witness = hashlib.sha256(
        f"{meter.segment_manifest_hash}:{meter.predecessor_ledger_hash}:{attributable}".encode()
    ).hexdigest()

    return {
        "bucket": "production",
        "sub_task_id": meter.sub_task_id,
        "tokens": attributable,
        "witness_hash": witness,
        "replayable": True,
    }
