"""
Module: src.shared.settings
Workorder: WO01
Purpose: Application settings loading for config and runtime defaults.

Dependencies:
    - pathlib: Path handling
    - os: Environment variable overrides
    - json: JSON config parsing

Inputs:
    - Config file paths

Outputs:
    - Settings dictionary for pipeline runtime

Key Functions/Classes:
    - load_settings: Reads application settings from YAML/JSON

Tests: tests/unit/test_placeholder.py
"""
from pathlib import Path
import json
import os
from typing import Any

from src.shared.errors import ConfigurationError


def load_settings(config_path: Path) -> dict[str, Any]:
    """Load settings from YAML or JSON file with environment overrides.

    Args:
        config_path: Path to settings file.

    Returns:
        Parsed settings dictionary.

    Raises:
        ConfigurationError: If settings file is missing or invalid.
    """
    if not config_path.exists():
        raise ConfigurationError(f"Config file not found: {config_path}")

    suffix = config_path.suffix.lower()
    if suffix in {".yaml", ".yml"}:
        try:
            import yaml  # type: ignore[import-not-found]
        except ModuleNotFoundError as error:
            raise ConfigurationError(
                "PyYAML is required to read YAML config files. Install 'pyyaml'."
            ) from error

        with config_path.open("r", encoding="utf-8") as file:
            parsed = yaml.safe_load(file)
    elif suffix == ".json":
        with config_path.open("r", encoding="utf-8") as file:
            parsed = json.load(file)
    else:
        raise ConfigurationError(
            f"Unsupported config format '{suffix}'. Use .yaml, .yml or .json."
        )

    if not isinstance(parsed, dict):
        raise ConfigurationError("Configuration root must be a key-value object.")

    runtime_section = parsed.setdefault("runtime", {})
    if not isinstance(runtime_section, dict):
        raise ConfigurationError("'runtime' section must be an object.")

    env_device = os.getenv("DEVICE")
    if env_device:
        runtime_section["device"] = env_device

    return parsed

