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


LEGACY_ENV_MAP = {
    "SMPAS_HOME": "MUSHROOM_HOME",
    "SMPAS_MODELS_DIR": "MUSHROOM_MODELS_DIR",
    "SMPAS_DATA_DIR": "MUSHROOM_DATA_DIR",
    "SMPAS_UPLOAD_DIR": "MUSHROOM_UPLOAD_DIR",
    "SMPAS_EXAMPLES_DIR": "MUSHROOM_EXAMPLES_DIR",
}


def _get_env(name: str) -> Optional[str]:
    value = os.getenv(name)
    if value:
        return value
    legacy = LEGACY_ENV_MAP.get(name)
    if legacy:
        return os.getenv(legacy)
    return None


def resolve_base_dir(base_dir: Optional[str] = None) -> Path:
    if base_dir:
        return Path(base_dir).expanduser()

    env_dir = _get_env("SMPAS_HOME")
    if env_dir:
        return Path(env_dir).expanduser()

    return Path.home() / ".smpas"


def ensure_app_dirs(base_dir: Path) -> Dict[str, Path]:
    dirs = {
        "base": base_dir,
        "models": base_dir / "models",
        "data": base_dir / "data",
        "outputs": base_dir / "outputs",
        "uploads": base_dir / "uploads",
    }

    for path in dirs.values():
        path.mkdir(parents=True, exist_ok=True)

    return dirs


def resolve_dir(
    base_dir: Path,
    override: Optional[str],
    env_name: str,
    default_subdir: str,
) -> Path:
    if override:
        return Path(override).expanduser()

    env_value = _get_env(env_name)
    if env_value:
        return Path(env_value).expanduser()

    return base_dir / default_subdir
