# retoor <retoor@molodetz.nl>

from .core import TTLCache, bump_cache_version, db, get_table, sync_local_cache


def internal_gateway_key() -> str:
    return get_setting("gateway_internal_key", "")


_settings_cache = TTLCache(ttl=60, max_size=100)


def get_setting(key: str, default: str = "") -> str:
    sync_local_cache("settings", _settings_cache)
    cached = _settings_cache.get(key)
    if cached is not None:
        return cached
    if "site_settings" not in db.tables:
        return default
    entry = db["site_settings"].find_one(key=key)
    if entry is None:
        return default
    _settings_cache.set(key, entry["value"])
    return entry["value"]


def get_int_setting(key: str, default: int) -> int:
    raw = get_setting(key, str(default))
    try:
        return int(raw)
    except (TypeError, ValueError):
        return default


def set_setting(key: str, value: str) -> None:
    settings = get_table("site_settings")
    existing = settings.find_one(key=key)
    if existing:
        settings.update({"id": existing["id"], "key": key, "value": value}, ["id"])
    else:
        settings.insert({"uid": f"setting_{key}", "key": key, "value": value})
    _settings_cache.set(key, value)
    bump_cache_version("settings")


def clear_settings_cache() -> None:
    _settings_cache.clear()
    bump_cache_version("settings")
