"""Generic JSON safety validators."""

from __future__ import annotations

import math

from pydantic import JsonValue


def validate_json_safe_dict(
    data: dict[str, JsonValue], *, prefix: str
) -> dict[str, JsonValue]:
    """Validate each value in a dict with ensure_finite_json and return it."""
    for key, value in data.items():
        ensure_finite_json(value, path=f"{prefix}.{key}")
    return data


def ensure_finite_json(value: JsonValue, *, path: str) -> None:
    """Reject non-finite numbers to preserve deterministic JSON contracts."""
    if isinstance(value, float):
        if not math.isfinite(value):
            raise ValueError(f"{path} must not contain NaN or infinity")
        return
    if isinstance(value, list):
        for index, item in enumerate(value):
            ensure_finite_json(item, path=f"{path}[{index}]")
        return
    if isinstance(value, dict):
        for key, item in value.items():
            ensure_finite_json(item, path=f"{path}.{key}")
        return
