# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-skill-whose-manifest-hash-matches-but-whose-tool-call-surface-has-drifted-the-post-load-capability-a.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-skill-whose-manifest-hash-matches-but-whose-tool-call-surface-has-drifted-the-post-load-capability-a.warrant.json
# Markdown SHA-256:   1d177223fa60757ddf8611ea79c8d89c5e240e52b211a582e7a216bd1ebff625
# Code AST SHA-256:   c39780b9499fef1539f3df2447d33d288cddeafce151615a123d3aa9ab6a997f
# Verified Classes:   CapabilityAttestationError, ToolDecl, Manifest, MaterializedTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityAttestationError(RuntimeError):
    """Raised when a materialized tool-call surface exceeds its declared manifest."""


@dataclass(frozen=True)
class ToolDecl:
    name: str
    side_effect_class: str  # ordered: "read" < "write" < "exec"
    scopes: tuple[str, ...]


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    version: str
    declared: Mapping[str, ToolDecl]
    manifest_sha256: str


@dataclass(frozen=True)
class MaterializedTool:
    name: str
    side_effect_class: str
    scopes: tuple[str, ...]


_SEVERITY = {"read": 0, "write": 1, "exec": 2}


def _verify_manifest_hash(manifest: Manifest, raw_manifest_bytes: bytes) -> None:
    if hashlib.sha256(raw_manifest_bytes).hexdigest() != manifest.manifest_sha256:
        raise CapabilityAttestationError(
            f"manifest hash mismatch for {manifest.skill_id}@{manifest.version}"
        )


def attest_materialized_surface(
    manifest: Manifest,
    materialized: list[MaterializedTool],
    scope_map: Mapping[str, tuple[str, ...]],
) -> list[MaterializedTool]:
    """
    Enforce: materialized surface must be a subset of declared, per tool,
    with side-effect class <= declared and a resolvable scope entry.
    Must run BEFORE the schema is exposed to the model.
    """
    added: list[str] = []
    escalated: list[str] = []
    scope_misses: list[str] = []

    for tool in materialized:
        decl = manifest.declared.get(tool.name)
        if decl is None:
            added.append(tool.name)
            continue
        if _SEVERITY.get(tool.side_effect_class, 99) > _SEVERITY.get(decl.side_effect_class, 99):
            escalated.append(
                f"{tool.name}:{decl.side_effect_class}->{tool.side_effect_class}"
            )
        if tool.name not in scope_map:
            scope_misses.append(tool.name)

    if added or escalated or scope_misses:
        raise CapabilityAttestationError(
            "materialized surface exceeds declared manifest "
            f"for {manifest.skill_id}@{manifest.version}: "
            f"added={added} escalated={escalated} scope_misses={scope_misses}"
        )

    # Safe: model-facing schema may now be built from `materialized`.
    return materialized


def load_skill(
    manifest: Manifest,
    raw_manifest_bytes: bytes,
    fetch_impl_tools,
    scope_map: Mapping[str, tuple[str, ...]],
) -> list[MaterializedTool]:
    _verify_manifest_hash(manifest, raw_manifest_bytes)
    materialized = fetch_impl_tools()  # lazy / codegen materialization
    # Attestation is per-materialization, never cached across re-fetch.
    return attest_materialized_surface(manifest, materialized, scope_map)
