# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distinguish-a-hallucinated-tool-call-from-a-genuine-call-to-a-tool-whose-schema-silently-drifted-and-why-the-trace-alone-cannot.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distinguish-a-hallucinated-tool-call-from-a-genuine-call-to-a-tool-whose-schema-silently-drifted-and-why-the-trace-alone-cannot.warrant.json
# Markdown SHA-256:   073fc0e401988d2771b5a47096f40183d1f434946f2a1f4781f03e09b8930956
# Code AST SHA-256:   9d0b06e6ab493d475bb9d475c9e4d0b2969d74367132cc6a523e312902cf92f8
# Verified Classes:   SchemaProvenanceError, SchemaDriftError, Descriptor, ToolUse
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class SchemaProvenanceError(RuntimeError):
    """Raised when a tool_use cannot be scored because its emission-time
    schema provenance is missing or does not match any known descriptor."""
    pass


class SchemaDriftError(RuntimeError):
    """Raised when the live server descriptor hash differs from the hash the
    instance pinned at discovery, and the caller has opted to fail closed."""
    pass


@dataclass(frozen=True)
class Descriptor:
    tool_name: str
    input_schema: dict[str, Any]

    @property
    def hash(self) -> str:
        canonical = json.dumps(
            {"name": self.tool_name, "inputSchema": self.input_schema},
            sort_keys=True, separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass(frozen=True)
class ToolUse:
    tool_name: str
    args: dict[str, Any]
    descriptor_hash: str | None  # None == provenance lost


def _conforms(args: dict[str, Any], schema: dict[str, Any]) -> bool:
    # Minimal structural check: required keys present, no extra keys,
    # enum membership honored. A production validator would use jsonschema.
    props = schema.get("properties", {})
    required = set(schema.get("required", []))
    if not required.issubset(args.keys()):
        return False
    if schema.get("additionalProperties", True) is False:
        if not set(args.keys()).issubset(props.keys()):
            return False
    for key, value in args.items():
        spec = props.get(key, {})
        if "enum" in spec and value not in spec["enum"]:
            return False
    return True


def classify_tool_use(
    use: ToolUse,
    descriptor_store: dict[str, Descriptor],   # hash -> descriptor, versioned
    live_descriptor: Descriptor,
) -> str:
    """Return 'drift' or 'hallucination'. Refuse to score without provenance."""
    if use.descriptor_hash is None:
        raise SchemaProvenanceError(
            f"tool_use for {use.tool_name!r} has no descriptor hash; "
            f"cannot distinguish drift from hallucination"
        )
    believed = descriptor_store.get(use.descriptor_hash)
    if believed is None:
        raise SchemaProvenanceError(
            f"descriptor hash {use.descriptor_hash[:12]} for "
            f"{use.tool_name!r} not found in versioned store"
        )

    valid_against_belief = _conforms(use.args, believed.input_schema)
    valid_against_live = _conforms(use.args, live_descriptor.input_schema)

    if valid_against_belief and not valid_against_live:
        return "drift"
    if not valid_against_belief:
        return "hallucination"
    # valid against both: coincidentally legitimized argument; treat as
    # hallucination-adjacent and route to review rather than success.
    if believed.hash != live_descriptor.hash and valid_against_live:
        return "hallucination"
    return "success"


def emit_call(
    tool_name: str,
    args: dict[str, Any],
    pinned: Descriptor,
    live: Descriptor,
    fail_closed: bool = True,
) -> ToolUse:
    if pinned.hash != live.hash and fail_closed:
        raise SchemaDriftError(
            f"{tool_name!r} drifted between discovery "
            f"({pinned.hash[:12]}) and invocation ({live.hash[:12]}); "
            f"re-discovery required before emitting"
        )
    return ToolUse(tool_name=tool_name, args=args, descriptor_hash=pinned.hash)
