"""Generic configuration loader utilities."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Any, cast

import yaml

logger = logging.getLogger(__name__)


def load_config() -> dict[str, Any]:
    """
    Load raw configuration from YAML file.

    Returns:
        Raw configuration dictionary
    """
    config_dir = None
    for parent in Path(__file__).resolve().parents:
        candidate = parent / "config"
        if candidate.is_dir():
            config_dir = candidate
            break
    if config_dir is None:
        return {}
    config_path = config_dir / "project_conventions.yaml"

    if not config_path.exists():
        # Expected when running from installed wheel (config not packaged). Avoid WARNING so MCP log stays clean.
        logger.debug("Config file not found: %s", config_path)
        return {}

    try:
        with open(config_path, encoding="utf-8") as f:
            result = yaml.safe_load(f)
            merged: dict[str, Any] = cast(dict[str, Any], result) if isinstance(result, dict) else {}

        # Optional: load additional configs (keep bundles out of code).
        # This file is intentionally separate so rule-path refactors don't touch Python code.
        injection_path = config_dir / "rules_injection.yaml"
        if "rules_injection" not in merged and injection_path.exists():
            try:
                with open(injection_path, encoding="utf-8") as f:
                    inj = yaml.safe_load(f)
                    if isinstance(inj, dict):
                        merged["rules_injection"] = cast(dict[str, Any], inj)
            except Exception as e:
                logger.warning("Failed to load optional config %s: %s", injection_path, e)

        return merged
    except Exception as e:
        logger.error(f"Error loading config: {e}")
        return {}
