# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-tool-return-taint-as-a-hard-egress-barrier-rather-than-advisory-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-tool-return-taint-as-a-hard-egress-barrier-rather-than-advisory-metadata.warrant.json
# Markdown SHA-256:   9f4de2792eb9e941b1b47643e9d63b60bad9472ed96fb4b0b733dfe876058d05
# Code AST SHA-256:   dd3348d2afbaa4e552d9ad163ad62a826838be1df8e569bec65c55f83d078ca8
# Verified Classes:   TaintBarrierViolation, ProvenanceEntry, ProvenanceLedger, DerivedPayload
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class TaintBarrierViolation(RuntimeError):
    """Raised when egress cannot be proven clean against the provenance ledger."""


@dataclass(frozen=True)
class ProvenanceEntry:
    content_hash: str
    tainted: bool
    origin: str


@dataclass
class ProvenanceLedger:
    entries: dict[str, ProvenanceEntry] = field(default_factory=dict)

    def record(self, payload: str, tainted: bool, origin: str) -> str:
        h = hashlib.sha256(payload.encode("utf-8")).hexdigest()
        self.entries[h] = ProvenanceEntry(h, tainted, origin)
        return h

    def lookup(self, payload: str) -> ProvenanceEntry | None:
        h = hashlib.sha256(payload.encode("utf-8")).hexdigest()
        return self.entries.get(h)


@dataclass
class DerivedPayload:
    text: str
    derived_from: tuple[str, ...] | None  # source hashes; None means no proof


def enforce_egress(
    outbound: DerivedPayload,
    ledger: ProvenanceLedger,
    *,
    allow_unknown: bool = False,
) -> None:
    """Hard-barrier egress check. Ignores any agent-declared taint state."""
    if outbound.derived_from is None:
        # No derivation proof: cannot verify provenance. Fail closed unless
        # explicitly configured otherwise for a known-clean channel.
        if not allow_unknown:
            raise TaintBarrierViolation(
                "egress blocked: payload has no derivation proof; "
                "cannot reconstruct provenance from content alone"
            )
        return

    if not outbound.derived_from:
        # Empty proof is treated as unproven, not as clean.
        raise TaintBarrierViolation(
            "egress blocked: empty derivation set is not evidence of clean provenance"
        )

    for source_hash in outbound.derived_from:
        entry = ledger.entries.get(source_hash)
        if entry is None:
            raise TaintBarrierViolation(
                f"egress blocked: derivation source {source_hash[:12]} not in ledger"
            )
        if entry.tainted:
            raise TaintBarrierViolation(
                f"egress blocked: payload derives from tainted source "
                f"{entry.origin} ({source_hash[:12]})"
            )


def serialize_handoff(payload: DerivedPayload, sidecar: dict | None) -> dict:
    """Fail-closed handoff serializer: a missing sidecar is a hard error."""
    if sidecar is None:
        raise TaintBarrierViolation(
            "handoff aborted: taint sidecar missing; refusing to default to clean"
        )
    return {"payload": payload.text, "derived_from": payload.derived_from, "sidecar": sidecar}
