"""
User configuration loader.

Reads ~/.depraptor/config.yaml and merges with CLI flags.
CLI flags always take precedence over config file values.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Optional

_CONFIG_PATH = Path.home() / ".depraptor" / "config.yaml"

_DEFAULTS: Dict[str, Any] = {
    "threads": 10,
    "default_payload": "system_info",
    "simulate": False,
    "npm_token": "",
    "pypi_token": "",
    "github_token": "",
    "verbose": False,
}


def load() -> Dict[str, Any]:
    """
    Load config from ~/.depraptor/config.yaml.
    Falls back to defaults if file is missing or malformed.
    """
    config = dict(_DEFAULTS)

    if not _CONFIG_PATH.exists():
        return config

    try:
        import yaml  # optional dependency
        raw = yaml.safe_load(_CONFIG_PATH.read_text(encoding="utf-8")) or {}
        config.update({k: v for k, v in raw.items() if k in _DEFAULTS})
    except Exception:
        pass  # silently fall back to defaults

    return config


def merge(config: Dict[str, Any], **cli_overrides: Any) -> Dict[str, Any]:
    """
    Merge CLI flag overrides into config dict.
    Only non-None CLI values override config.
    """
    merged = dict(config)
    for key, value in cli_overrides.items():
        if value is not None:
            merged[key] = value
    return merged


def ensure_config_dir() -> None:
    """Create ~/.depraptor/ if it doesn't exist."""
    _CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)


def write_default_config() -> None:
    """Write a default config file if none exists."""
    ensure_config_dir()
    if _CONFIG_PATH.exists():
        return
    try:
        import yaml
        _CONFIG_PATH.write_text(
            yaml.dump(_DEFAULTS, default_flow_style=False), encoding="utf-8"
        )
    except Exception:
        pass
