"""Load and access config/config.yaml.

Every script and runtime module reads the same YAML file so behavior is configured in one place.
Access nested keys with dotted paths: cfg.get("retrieval.top_k", 4).
"""
from __future__ import annotations

import os
from pathlib import Path
from typing import Any

import yaml

# Project root = two levels up from this file (src/agent/settings.py -> project root).
PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_CONFIG = PROJECT_ROOT / "config" / "config.yaml"


class Config:
    """Thin wrapper over the parsed YAML with dotted-path access and path resolution."""

    def __init__(self, data: dict[str, Any], path: Path):
        self._data = data
        self.path = path

    def get(self, dotted_key: str, default: Any = None) -> Any:
        node: Any = self._data
        for part in dotted_key.split("."):
            if not isinstance(node, dict) or part not in node:
                return default
            node = node[part]
        return node

    def resolve(self, dotted_key: str, default: str | None = None) -> Path:
        """Resolve a config value that is a path, relative to the project root."""
        value = self.get(dotted_key, default)
        if value is None:
            raise KeyError(f"Missing path config key: {dotted_key}")
        p = Path(value)
        return p if p.is_absolute() else (PROJECT_ROOT / p)

    @property
    def data(self) -> dict[str, Any]:
        return self._data


def load_config(path: str | os.PathLike | None = None) -> Config:
    cfg_path = Path(path) if path else DEFAULT_CONFIG
    if not cfg_path.is_absolute():
        cfg_path = PROJECT_ROOT / cfg_path
    with open(cfg_path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f) or {}
    return Config(data, cfg_path)
