"""Load Folio YAML config merged with environment (secrets via .env)."""

from __future__ import annotations

import os
from importlib import resources
from pathlib import Path
from typing import Any


def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
    out = dict(base)
    for k, v in override.items():
        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
            out[k] = _deep_merge(out[k], v)
        else:
            out[k] = v
    return out


def _bundled_defaults_text() -> str | None:
    """YAML shipped inside the wheel/sdist (pip install)."""
    try:
        ref = resources.files("folio_notion").joinpath("data/defaults.example.yaml")
    except (ModuleNotFoundError, TypeError):
        return None
    if not ref.is_file():
        return None
    return ref.read_text(encoding="utf-8")


def load_config(project_root: Path, config_path: Path | None = None) -> dict[str, Any]:
    try:
        import yaml
    except ImportError as e:
        raise RuntimeError("PyYAML is required for `fn run`. pip install pyyaml") from e

    path = config_path
    if path is None:
        env_p = os.environ.get("FOLIO_CONFIG")
        path = Path(env_p).expanduser() if env_p else project_root / "config" / "config.yaml"

    defaults: dict[str, Any] = {}
    example = project_root / "config" / "defaults.example.yaml"
    if example.is_file():
        defaults = yaml.safe_load(example.read_text(encoding="utf-8")) or {}
    else:
        bundled = _bundled_defaults_text()
        if bundled:
            defaults = yaml.safe_load(bundled) or {}

    if not path.is_file():
        merged = dict(defaults)
    else:
        user = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
        merged = _deep_merge(defaults, user)

    # Env overlays (for CI / .env)
    if os.environ.get("FOLIO_INPUT_DIR"):
        merged["input_dir"] = os.environ["FOLIO_INPUT_DIR"]
    if os.environ.get("FOLIO_EXPORT_DIR"):
        merged["export_dir"] = os.environ["FOLIO_EXPORT_DIR"]
    if os.environ.get("NOTION_PARENT_PAGE_ID"):
        notion = merged.get("notion") or {}
        notion["parent_page_id"] = os.environ["NOTION_PARENT_PAGE_ID"]
        merged["notion"] = notion
    if os.environ.get("FOLIO_NOTEBOOKLM_NOTEBOOK_ID"):
        nbl = merged.get("notebooklm") or {}
        nbl["notebook_id"] = os.environ["FOLIO_NOTEBOOKLM_NOTEBOOK_ID"]
        merged["notebooklm"] = nbl

    return merged
