from __future__ import annotations

"""Loading of profile definitions from JSON or YAML files.

Profiles provide a higher-level grouping of dataset recipes. For simple use
cases a built-in :data:`PROFILE_DEFINITIONS` mapping in ``recipes.__init__``
is sufficient, but users may also wish to maintain their own profile
configuration files. This module handles the latter.

The expected config shape is intentionally minimal::

    {
      "profiles": {
        "graphrag": ["rag_chunks", "basic_qa"],
        "qa_only": ["basic_qa"]
      }
    }

Each profile name maps to a list of recipe ``kind`` strings, which will be
fed into :func:`execute_profile`.
"""

from pathlib import Path

from .base import RecipeConfigError, _load_raw_config


def load_profiles_from_file(path: str | Path) -> dict[str, list[str]]:
    """Load profile definitions from a JSON or YAML file.

    The file must contain a top-level ``"profiles"`` key mapping profile
    names (strings) to lists of recipe kind strings. For example::

        {
          "profiles": {
            "graphrag": ["rag_chunks", "basic_qa"],
            "qa_only": ["basic_qa"]
          }
        }

    Any structural problems result in :class:`RecipeConfigError`.
    """

    p = Path(path)
    data = _load_raw_config(p)

    raw_profiles = data.get("profiles")
    if not isinstance(raw_profiles, dict):
        raise RecipeConfigError(
            "Profiles config must contain a 'profiles' mapping of profile "
            "names to lists of recipe kind strings."
        )

    result: dict[str, list[str]] = {}
    for name, kinds in raw_profiles.items():
        if not isinstance(name, str):
            raise RecipeConfigError(
                "Profile names in 'profiles' mapping must be strings."
            )
        if not isinstance(kinds, list) or not all(isinstance(k, str) for k in kinds):
            raise RecipeConfigError(
                f"Profile {name!r} must map to a list of recipe kind strings."
            )
        result[name] = list(kinds)

    return result

