"""Client settings loader for STARWASTE.

Goal: lightweight, cross-platform, no extra dependencies.

Settings are read from JSON. Search order:
1) Local file in current working directory: starwaste_settings.json
2) User config directory (OS-specific): <config_dir>/starwaste/settings.json

Environment variables may still override some settings elsewhere.
"""

from __future__ import annotations

import json
import os
import platform
from pathlib import Path
from typing import Any, Dict, Optional


def _user_config_dir() -> Path:
    system = platform.system().lower()

    if system == "windows":
        base = os.getenv("APPDATA") or os.getenv("LOCALAPPDATA")
        if base:
            return Path(base)
        return Path.home() / "AppData" / "Roaming"

    if system == "darwin":
        return Path.home() / "Library" / "Application Support"

    # linux + other unix
    xdg = os.getenv("XDG_CONFIG_HOME")
    if xdg:
        return Path(xdg)
    return Path.home() / ".config"


def _settings_paths() -> list[Path]:
    return [
        Path.cwd() / "starwaste_settings.json",
        _user_config_dir() / "starwaste" / "settings.json",
    ]


def load_settings() -> Dict[str, Any]:
    for path in _settings_paths():
        try:
            if path.exists():
                return json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            continue
    return {}


def save_settings(settings: Dict[str, Any]) -> bool:
    """Persist settings to user config file (not the cwd file)."""
    try:
        path = _user_config_dir() / "starwaste" / "settings.json"
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(settings, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        return True
    except Exception:
        return False


def get_language(settings: Optional[Dict[str, Any]] = None) -> Optional[str]:
    settings = settings if isinstance(settings, dict) else load_settings()
    lang = settings.get("language")
    if isinstance(lang, str) and lang.strip():
        return lang.strip()
    return None


def set_language(language: str) -> bool:
    s = load_settings()
    s["language"] = language
    return save_settings(s)
