import json
import os

def _config_dir():
    if os.name == "nt":
        base = os.environ.get("APPDATA") or os.path.expanduser("~")
    else:
        base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
    return os.path.join(base, "abuz_solver")

def _config_path():
    return os.path.join(_config_dir(), "config.json")

def load():
    p = _config_path()
    if not os.path.isfile(p):
        return None
    try:
        with open(p, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return None

def save_url(server_url: str):
    d = _config_dir()
    os.makedirs(d, exist_ok=True)
    p = _config_path()
    data = load() or {}
    data["url"] = server_url.rstrip("/")
    with open(p, "w", encoding="utf-8") as f:
        json.dump(data, f)
    try:
        os.chmod(p, 0o600)
    except Exception:
        pass


