"""
settings.py — Application settings model and JSON persistence.

File location
-------------
Windows : %APPDATA%\\Powernet\\settings.json
macOS   : ~/Library/Application Support/Powernet/settings.json
Linux   : $XDG_DATA_HOME/Powernet/settings.json  (~/.local/share/Powernet/settings.json)
"""

from __future__ import annotations

import json
import os
import sys
from dataclasses import asdict, dataclass
from pathlib import Path


def app_data_dir() -> Path:
    """Return the platform-appropriate application data root for Powernet."""
    if sys.platform == "win32":
        base = Path(os.environ.get("APPDATA", Path.home()))
    elif sys.platform == "darwin":
        base = Path.home() / "Library" / "Application Support"
    else:
        xdg = os.environ.get("XDG_DATA_HOME", "")
        base = Path(xdg) if xdg else Path.home() / ".local" / "share"
    return base / "Powernet"


_SETTINGS_FILE = app_data_dir() / "settings.json"


@dataclass
class Settings:
    fps_limit: int   = 60      # 0 = unlimited
    volume_music: int = 55     # 0–100
    volume_sounds: int = 80    # 0–100
    volume_buildings: int = 80 # 0–100
    language: str = "en"       # "en" | "de" | "nl" | "fr"
    fullscreen: bool = False
    resolution_w: int = 1280
    resolution_h: int = 720
    ui_scale: int = 2          # 1–4 (0.75x / 1.0x / 1.25x / 1.5x)
    title_glow: bool = True    # main menu title glow effect
    colorblind_mode: bool = False  # higher contrast colours

    def save(self) -> None:
        _SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
        with open(_SETTINGS_FILE, "w", encoding="utf-8") as fh:
            json.dump(asdict(self), fh, indent=2)

    @classmethod
    def load(cls) -> "Settings":
        if not _SETTINGS_FILE.exists():
            s = cls()
            s.save()
            return s
        try:
            with open(_SETTINGS_FILE, encoding="utf-8") as fh:
                data = json.load(fh)
            known = set(cls.__dataclass_fields__)
            return cls(**{k: v for k, v in data.items() if k in known})
        except Exception:
            return cls()


# ---------------------------------------------------------------------------
# Global singleton (lazy-loaded)
# ---------------------------------------------------------------------------

_instance: Settings | None = None


def get_settings() -> Settings:
    global _instance
    if _instance is None:
        _instance = Settings.load()
    return _instance


def reload_settings() -> Settings:
    """Force reload from disk (e.g. after external edit)."""
    global _instance
    _instance = Settings.load()
    return _instance
