# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-tainted-provenance-across-a-tool-boundary-when-a-downstream-tool-re-derives-the-same-value-from-a-clean-source.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-tainted-provenance-across-a-tool-boundary-when-a-downstream-tool-re-derives-the-same-value-from-a-clean-source.warrant.json
# Markdown SHA-256:   3beb243ed281c31bdb763bdf9354e06b4d65b55977f93dd13b6bdf1f5d4848e7
# Code AST SHA-256:   0b4f80d197fdbcdf58bf93df1a7da0ad3d4fe5899964faf31812cae8fe75b33b
# Verified Classes:   TaintLevel, Segment, TaintLaunderingError, ContextStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintLevel(IntEnum):
    TRUSTED = 0
    TOOL_OUTPUT = 1
    UNTRUSTED_WEB = 2
    UNTRUSTED_INJECTED = 3


@dataclass(frozen=True)
class Segment:
    content: str
    taint: TaintLevel
    source_id: str

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode("utf-8")).hexdigest()


class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary would lower taint without declassification."""


@dataclass
class ContextStore:
    # keyed by (content_hash, taint) so equal content with different taint
    # never collapses into one entry.
    _entries: dict[tuple[str, TaintLevel], Segment] = field(default_factory=dict)

    def insert(self, seg: Segment) -> None:
        self._entries[(seg.content_hash, seg.taint)] = seg

    def live_taints_for(self, content: str) -> set[TaintLevel]:
        h = hashlib.sha256(content.encode("utf-8")).hexdigest()
        return {t for (ch, t) in self._entries if ch == h}


def tool_return(
    store: ContextStore,
    tool_name: str,
    output_content: str,
    input_segments: Iterable[Segment],
    derived_from_attested: bool,
) -> Segment:
    """Apply the join-and-shadow invariant at a tool boundary."""
    inputs = list(input_segments)
    if not inputs:
        raise TaintLaunderingError(
            f"tool {tool_name} returned without declared inputs; cannot compute join"
        )

    if derived_from_attested:
        out_taint = max(s.taint for s in inputs)
    else:
        # Echoing / unattested tool: propagate full input taint, never lower.
        out_taint = max([s.taint for s in inputs] + [TaintLevel.TOOL_OUTPUT])

    seg = Segment(content=output_content, taint=out_taint, source_id=f"{tool_name}#out")

    # Shadow check: if any live segment with identical content carries a
    # strictly higher taint, the new segment must not be treated as clean.
    live = store.live_taints_for(output_content)
    if live:
        highest = max(live)
        if out_taint < highest:
            raise TaintLaunderingError(
                f"tool {tool_name} would launder content: out_taint={out_taint.name} "
                f"but live taint {highest.name} exists for same content_hash"
            )
    store.insert(seg)
    return seg


def guarded_write(store: ContextStore, path: str, content: str) -> None:
    """A sink requiring trusted input must reject if ANY tainted twin exists."""
    live = store.live_taints_for(content)
    if any(t > TaintLevel.TOOL_OUTPUT for t in live):
        raise TaintLaunderingError(
            f"refusing write to {path}: content has untrusted twin "
            f"(taints={sorted(t.name for t in live)})"
        )
    # perform write
    return None
