"""Persistent user settings backed by a JSON file."""

from __future__ import annotations

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


def _get_config_dir() -> Path:
    base = os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))
    return Path(base) / "chess-cli"


def _get_settings_path() -> Path:
    return _get_config_dir() / "settings.json"


@dataclass
class Settings:
    show_undo_button: bool = False
    lichess_api_token: str = ""
    # Engine settings
    engine_profile: str = "Quick"
    difficulty: str = "intermediate"
    custom_threads: int = 1
    custom_hash_mb: int = 16
    custom_move_time_index: int = 0
    # Lichess settings
    lichess_time_control_index: int = 1


def load_settings() -> Settings:
    """Load settings from disk, returning defaults on any error."""
    try:
        data = json.loads(_get_settings_path().read_text())
        valid_keys = {f.name for f in fields(Settings)}
        return Settings(**{k: v for k, v in data.items() if k in valid_keys})
    except Exception:
        return Settings()


def save_settings(settings: Settings) -> None:
    """Persist settings to disk. Silently ignores write errors."""
    try:
        path = _get_settings_path()
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(asdict(settings), indent=2) + "\n")
    except OSError:
        pass
