"""Persistent configuration for nanoleaf-ctl.

Stores device IP and auth token in ~/.config/nanoleaf-ctl/config.json
so you don't have to re-authenticate every time.
"""

import json
from pathlib import Path

CONFIG_DIR = Path.home() / ".config" / "nanoleaf-ctl"
CONFIG_FILE = CONFIG_DIR / "config.json"


def load() -> dict:
    """Load saved configuration, returning empty dict if none exists."""
    if not CONFIG_FILE.exists():
        return {}
    return json.loads(CONFIG_FILE.read_text())


def save(cfg: dict) -> None:
    """Persist configuration to disk."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(cfg, indent=2) + "\n")


def get_device() -> tuple[str | None, str | None]:
    """Return (ip, auth_token) from saved config."""
    cfg = load()
    return cfg.get("ip"), cfg.get("auth_token")


def save_device(ip: str, auth_token: str) -> None:
    """Save device IP and auth token."""
    cfg = load()
    cfg["ip"] = ip
    cfg["auth_token"] = auth_token
    save(cfg)


def clear() -> None:
    """Remove saved configuration."""
    if CONFIG_FILE.exists():
        CONFIG_FILE.unlink()
