import shutil
from pathlib import Path
from typing import Any

import yaml

_CONFIG_DIR = Path.home() / ".config" / "minimls"
_CONFIG_PATH = _CONFIG_DIR / "config.yaml"
_TEMPLATE_PATH = Path(__file__).parent / "templates" / "config.yaml"


def _ensure_config_file() -> None:
    if not _CONFIG_PATH.exists():
        _CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        shutil.copy(_TEMPLATE_PATH, _CONFIG_PATH)


def load_config() -> dict[str, Any]:
    _ensure_config_file()
    with _CONFIG_PATH.open() as f:
        return yaml.safe_load(f)


def get_env_config(env: str) -> dict[str, str]:
    config = load_config()
    if env not in config:
        raise KeyError(f"env {env!r} not found in {_CONFIG_PATH}")
    return config[env]
