"""Persistent configuration management for ceraviz.

Stores the API key in a platform-appropriate config directory so users
don't need to re-enter it every session.

Storage location: ~/.config/ceraviz/config.json
"""

import json
import os
from pathlib import Path
from typing import Optional


_CONFIG_DIR = Path.home() / ".config" / "ceraviz"
_CONFIG_FILE = _CONFIG_DIR / "config.json"


def _load_config() -> dict:
    """Load config from disk, returning empty dict if not found."""
    if _CONFIG_FILE.exists():
        try:
            return json.loads(_CONFIG_FILE.read_text())
        except (json.JSONDecodeError, OSError):
            return {}
    return {}


def _save_config(config: dict) -> None:
    """Save config to disk, creating the directory if needed."""
    _CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    _CONFIG_FILE.write_text(json.dumps(config, indent=2) + "\n")


def get_stored_api_key() -> Optional[str]:
    """Get the stored API key, or None if not set."""
    return _load_config().get("api_key")


def store_api_key(key: str) -> None:
    """Persist an API key to the config file."""
    config = _load_config()
    config["api_key"] = key
    _save_config(config)


def clear_api_key() -> None:
    """Remove the stored API key."""
    config = _load_config()
    config.pop("api_key", None)
    _save_config(config)
