"""Load and save user-adjusted GUI settings beside the application.

The settings live in a human-readable ``qtfm_settings.json`` in the folder
the executable runs from (the source folder when running from source), so
they are always easy to find, copy, or delete. A missing or unreadable file
simply yields defaults.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

SETTINGS_FILENAME = "qtfm_settings.json"


def settings_path() -> Path:
    """Return the settings file location next to the running program."""
    if getattr(sys, "frozen", False):
        return Path(sys.executable).resolve().parent / SETTINGS_FILENAME
    return Path(__file__).resolve().parent / SETTINGS_FILENAME


def load_settings() -> dict:
    """Return the saved settings, or an empty dict when none are usable."""
    try:
        with settings_path().open(encoding="utf-8") as settings_file:
            data = json.load(settings_file)
    except (OSError, ValueError):
        return {}
    return data if isinstance(data, dict) else {}


def save_settings(settings: dict) -> bool:
    """Write the settings; return False when the folder is not writable."""
    try:
        settings_path().write_text(
            json.dumps(settings, indent=2) + "\n",
            encoding="utf-8",
        )
    except OSError:
        return False
    return True
