"""Config loader — reads config from file or returns defaults."""

from __future__ import annotations

import json
import logging
from pathlib import Path

from dpe.models.config import DPEConfig

logger = logging.getLogger(__name__)


def load_config(path: str | Path | None = None, **overrides: object) -> DPEConfig:
    """Load DPE config from a JSON file, with optional overrides.

    If no path is given, returns default config with overrides applied.
    """
    if path is not None:
        p = Path(path)
        if not p.exists():
            raise FileNotFoundError(f"Config file not found: {p}")

        raw = p.read_text(encoding="utf-8")
        try:
            data = json.loads(raw)
        except json.JSONDecodeError as e:
            raise ValueError(f"Invalid JSON in config file: {e}") from e

        data.update(overrides)
        config = DPEConfig.model_validate(data)
    else:
        config = DPEConfig.model_validate(overrides)

    logger.info(
        "Config loaded (hash=%s, simulation=%s)",
        config.config_hash()[:12],
        config.simulation_mode,
    )
    return config
