"""Supply chain monitoring — schema extraction and hashing for tool responses."""

from __future__ import annotations

import hashlib
import json
from typing import Any


def extract_schema(data: Any) -> Any:
    """Recursively extract the structural schema from any value.

    Returns a normalized representation where values are replaced by type strings.
    Keys are sorted alphabetically for deterministic output.
    """
    if data is None:
        return "null"
    if isinstance(data, bool):
        return "boolean"
    if isinstance(data, (int, float)):
        return "number"
    if isinstance(data, str):
        return "string"
    if isinstance(data, list):
        if len(data) == 0:
            return "array<empty>"
        elem_type = extract_schema(data[0])
        if isinstance(elem_type, dict):
            return "array<object>"
        return f"array<{elem_type}>"
    if isinstance(data, dict):
        schema: dict[str, Any] = {}
        for key in sorted(data.keys()):
            schema[key] = extract_schema(data[key])
        return schema
    return "unknown"


def hash_schema(schema: Any) -> str:
    """Deterministically hash a schema structure.

    Produces the same SHA-256 hex digest regardless of original key order.
    """
    normalized = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(normalized.encode()).hexdigest()
