"""XDG Base Directory Spec paths for stable-delusion."""

__author__ = "Lene Preuss <lene.preuss@gmail.com>"

import json
import os
from pathlib import Path


def xdg_config_home() -> Path:
    """Return XDG_CONFIG_HOME, defaulting to ~/.config."""
    return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))


def xdg_data_home() -> Path:
    """Return XDG_DATA_HOME, defaulting to ~/.local/share."""
    return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))


def xdg_cache_home() -> Path:
    """Return XDG_CACHE_HOME, defaulting to ~/.cache."""
    return Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))


def config_dir() -> Path:
    """Return the stable-delusion config directory."""
    return xdg_config_home() / "stable-delusion"


def data_dir() -> Path:
    """Return the stable-delusion data directory."""
    return xdg_data_home() / "stable-delusion"


def cache_dir() -> Path:
    """Return the stable-delusion cache directory."""
    return xdg_cache_home() / "stable-delusion"


def default_projects_dir() -> Path:
    """Return the default projects directory inside XDG data home."""
    return data_dir() / "projects"


def resolve_projects_dir(override: Path | None = None) -> Path:
    """
    Resolve the projects directory from multiple sources (highest priority first):
    1. override argument (e.g. --projects-dir flag)
    2. STABLE_DELUSION_PROJECTS_DIR environment variable
    3. projects_dir in ~/.config/stable-delusion/config.json
    4. Default: XDG_DATA_HOME/stable-delusion/projects/
    """
    if override is not None:
        return override
    env = os.environ.get("STABLE_DELUSION_PROJECTS_DIR")
    if env:
        return Path(env)
    config_file = config_dir() / "config.json"
    if config_file.exists():
        data = json.loads(config_file.read_text(encoding="utf-8"))
        if "projects_dir" in data:
            return Path(data["projects_dir"])
    return default_projects_dir()
