"""Token file loading utilities."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict

import yaml

from tokenmoulds.dtcg.errors import TokenLoadError


def load_token_file(path: Path) -> Dict[str, Any]:
    """Load a token file from JSON or YAML."""
    if not path.exists():
        raise TokenLoadError(f"Token file not found: {path}")

    suffix = path.suffix.lower()
    if suffix in {".yaml", ".yml"}:
        try:
            with path.open("r", encoding="utf-8") as handle:
                data = yaml.safe_load(handle)
        except yaml.YAMLError as exc:
            raise TokenLoadError(f"Invalid YAML in {path}: {exc}") from exc
    elif suffix == ".json":
        try:
            with path.open("r", encoding="utf-8") as handle:
                data = json.load(handle)
        except json.JSONDecodeError as exc:
            raise TokenLoadError(f"Invalid JSON in {path}: {exc.msg}") from exc
    else:
        raise TokenLoadError(f"Unsupported token file extension: {path.suffix}")

    if not isinstance(data, dict):
        raise TokenLoadError(f"Token file must contain an object at top level: {path}")

    return data
