from __future__ import annotations

import copy
import json
from importlib.resources import files
from typing import Any


_RESOURCE_ROOT = files("kernite")


def _load_json_resource(relative_path: str) -> Any:
    payload = _RESOURCE_ROOT.joinpath(relative_path).read_text(encoding="utf-8")
    return json.loads(payload)


def load_execute_vectors_v1() -> list[dict[str, Any]]:
    vectors = _load_json_resource("contracts/v1/execute_vectors.json")
    if not isinstance(vectors, list):
        raise ValueError("contracts/v1/execute_vectors.json must be a JSON array")
    return copy.deepcopy(vectors)


def load_reason_codes_v1() -> dict[str, str]:
    reason_codes = _load_json_resource("contracts/v1/reason_codes_v1.json")
    if not isinstance(reason_codes, dict):
        raise ValueError("contracts/v1/reason_codes_v1.json must be a JSON object")
    normalized: dict[str, str] = {}
    for key, value in reason_codes.items():
        normalized[str(key)] = str(value)
    return normalized


def load_execute_request_template() -> dict[str, Any]:
    payload = _load_json_resource("templates/execute-request.template.json")
    if not isinstance(payload, dict):
        raise ValueError(
            "templates/execute-request.template.json must be a JSON object"
        )
    return copy.deepcopy(payload)


def load_policy_version_template() -> dict[str, Any]:
    payload = _load_json_resource("templates/policy-version.template.json")
    if not isinstance(payload, dict):
        raise ValueError("templates/policy-version.template.json must be a JSON object")
    return copy.deepcopy(payload)
