"""Load and validate configuration from config.yaml + .env"""

import os
from pathlib import Path
from typing import Any

import yaml
from dotenv import load_dotenv


def load_config(config_path: str = "config.yaml") -> dict[str, Any]:
    """Load config.yaml and .env, return merged config dict."""
    load_dotenv()

    with open(config_path, "r", encoding="utf-8") as f:
        cfg = yaml.safe_load(f)

    # Inject secrets from env
    cfg["telegram"] = {
        "bot_token": _require_env("TELEGRAM_BOT_TOKEN"),
        "chat_id": _require_env("TELEGRAM_CHAT_ID"),
    }
    cfg["gemini_api_key"] = _require_env("GEMINI_API_KEY")

    # Ensure temp dir exists
    temp_dir = cfg.get("temp_dir", "/tmp/tapo-monitor")
    Path(temp_dir).mkdir(parents=True, exist_ok=True)

    # Ensure events DB dir exists
    events_db = cfg.get("events_db", "/var/lib/tapo-monitor/events.db")
    Path(events_db).parent.mkdir(parents=True, exist_ok=True)

    return cfg


def _require_env(key: str) -> str:
    val = os.environ.get(key)
    if not val:
        raise RuntimeError(f"Missing required environment variable: {key}")
    return val
