"""Serialization helpers for JSON and YAML files."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import yaml


def load_data(path: Path) -> dict[str, Any]:
    """Load structured data from a JSON or YAML file."""

    suffix = path.suffix.lower()
    text = path.read_text(encoding="utf-8")

    if suffix == ".json":
        data = json.loads(text)
    elif suffix in {".yaml", ".yml"}:
        data = yaml.safe_load(text)
    else:
        raise ValueError(f"unsupported file format: {suffix}")

    if not isinstance(data, dict):
        raise ValueError("expected top-level mapping")
    return data


def dump_data(path: Path, payload: dict[str, Any]) -> None:
    """Write structured data to a JSON or YAML file."""

    suffix = path.suffix.lower()
    path.parent.mkdir(parents=True, exist_ok=True)

    if suffix == ".json":
        text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    elif suffix in {".yaml", ".yml"}:
        text = yaml.safe_dump(payload, sort_keys=False, allow_unicode=True)
    else:
        raise ValueError(f"unsupported file format: {suffix}")

    path.write_text(text, encoding="utf-8")
