"""Shared fail-closed UTF-8 JSON loader for every rehearsal raw-input boundary."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any

def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    output: dict[str, Any] = {}
    for key, value in pairs:
        if key in output:
            raise ValueError(f"duplicate JSON object member: {key}")
        output[key] = value
    return output

def load_json_bytes(raw: bytes, label: str) -> Any:
    try:
        return json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs)
    except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:
        raise ValueError(f"{label} must be duplicate-free UTF-8 JSON: {exc}") from exc

def load_json_file(path: Path, label: str) -> Any:
    try:
        return load_json_bytes(path.read_bytes(), label)
    except OSError as exc:
        raise ValueError(f"cannot read {label}: {exc}") from exc
