# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-skill-manifest-and-the-mutable-registry-index-that-resolves-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-skill-manifest-and-the-mutable-registry-index-that-resolves-it.warrant.json
# Markdown SHA-256:   c3a11d1c868fea69c64bef3714e9f5984104646ce2a317c2fd6ff1e095c35d7a
# Code AST SHA-256:   389e9b5e6463270541c69b7084e8594a75284a3fbd3a524a01256f54ba56be79
# Verified Classes:   SkillTrustViolation, SkillPin, ResolvedSkill
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SkillTrustViolation(RuntimeError):
    """Raised when a resolved skill fails the pin-comparison gate.

    Distinct from a signature failure: the manifest may be validly signed
    and still trip this because the *resolution* was manipulated.
    """


@dataclass(frozen=True)
class SkillPin:
    skill_id: str
    version: str
    digest: str
    publisher_key: str


@dataclass(frozen=True)
class ResolvedSkill:
    skill_id: str
    version: str
    manifest_bytes: bytes
    publisher_key: str

    @property
    def digest(self) -> str:
        return "sha256:" + hashlib.sha256(self.manifest_bytes).hexdigest()


def load_skill(
    resolved: ResolvedSkill,
    pin: Optional[SkillPin],
    signature_valid: bool,
    rollback_authorized: bool = False,
) -> SkillPin:
    """Gate skill load on pin comparison, not on signature alone.

    signature_valid must be True to proceed at all; it is a precondition,
    not a substitute for the pin check.
    """
    if not signature_valid:
        raise SkillTrustViolation(
            f"signature invalid for {resolved.skill_id}@{resolved.version}"
        )

    if pin is None:
        # Trust-on-first-use: record the resolved tuple as the new pin.
        return SkillPin(
            skill_id=resolved.skill_id,
            version=resolved.version,
            digest=resolved.digest,
            publisher_key=resolved.publisher_key,
        )

    if resolved.skill_id != pin.skill_id:
        raise SkillTrustViolation(
            f"resolved skill_id {resolved.skill_id!r} != pinned {pin.skill_id!r}"
        )

    if resolved.publisher_key != pin.publisher_key:
        # Publisher confusion: manifest validly signed, but by the wrong key.
        raise SkillTrustViolation(
            f"publisher key mismatch for {pin.skill_id}: "
            f"pinned {pin.publisher_key!r}, resolved {resolved.publisher_key!r}"
        )

    if resolved.digest != pin.digest:
        # Downgrade or substitution: resolver returned different content.
        if resolved.version < pin.version and not rollback_authorized:
            raise SkillTrustViolation(
                f"downgrade refused for {pin.skill_id}: "
                f"pinned {pin.version} ({pin.digest}), "
                f"resolved {resolved.version} ({resolved.digest})"
            )
        raise SkillTrustViolation(
            f"digest mismatch for {pin.skill_id}@{pin.version}: "
            f"pinned {pin.digest}, resolved {resolved.digest}"
        )

    return pin
