"""Load extractor configuration from a TOML file."""

from __future__ import annotations

import os
import re
from pathlib import Path
from typing import Any

_ENV_VAR_RE = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)\}")


def _interpolate(value: str) -> str:
    """Replace ${VAR} with os.environ[VAR]. Raises KeyError if missing."""

    def _replace(m: re.Match) -> str:
        name = m.group(1)
        val = os.environ.get(name)
        if val is None:
            raise KeyError(f"Config references undefined env var: {name}")
        return val

    return _ENV_VAR_RE.sub(_replace, value)


def _walk(obj: Any) -> Any:
    if isinstance(obj, str):
        return _interpolate(obj)
    if isinstance(obj, dict):
        return {k: _walk(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [_walk(v) for v in obj]
    return obj


def load_config(path: Path | None = None) -> dict[str, Any]:
    """Load config from path, or search ./extractor.toml and ./.extractor.toml.
    Returns empty dict if no config file found."""
    candidates: list[Path] = []
    if path is not None:
        candidates = [path]
    else:
        cwd = Path.cwd()
        candidates = [cwd / "extractor.toml", cwd / ".extractor.toml"]

    for p in candidates:
        if p.exists():
            try:
                import tomllib  # Python 3.11+
            except ImportError:
                try:
                    import tomli as tomllib  # type: ignore[no-redef]
                except ImportError:
                    return {}
            with open(p, "rb") as f:
                raw = tomllib.load(f)
            return _walk(raw)
    return {}
