"""
wivexx_settings.py — tiny runtime user-settings store  (v1.24)
═══════════════════════════════════════════════════════════════════════════
Holds preferences the user changes from the control room AT RUNTIME (e.g. the
chosen microphone) WITHOUT editing wivexx_config.py. Backed by a small JSON file
that always lives next to this module, so it works even when the silent VBS
launcher starts the process with a stripped environment.

Public API:
    get(key, default=None) -> value
    set(key, value) -> bool        # value=None deletes the key
    all() -> dict
"""
import json
import os
import threading

_HERE = os.path.dirname(os.path.abspath(__file__))
_PATH = os.path.join(_HERE, "wivexx_settings.json")
_lock = threading.Lock()
_cache = None


def _load() -> dict:
    global _cache
    if _cache is None:
        try:
            with open(_PATH, encoding="utf-8") as f:
                data = json.load(f)
            _cache = data if isinstance(data, dict) else {}
        except Exception:
            _cache = {}
    return _cache


def get(key, default=None):
    with _lock:
        return _load().get(key, default)


def set(key, value) -> bool:
    with _lock:
        d = _load()
        if value is None:
            d.pop(key, None)
        else:
            d[key] = value
        try:
            with open(_PATH, "w", encoding="utf-8") as f:
                json.dump(d, f, indent=2)
            return True
        except Exception:
            return False


def all() -> dict:
    with _lock:
        return dict(_load())
