"""Configuration management — ~/.acl/config.json."""

import json
import os
import stat
from pathlib import Path
from typing import Any

import typer

CONFIG_DIR = Path.home() / ".acl"
CONFIG_FILE = CONFIG_DIR / "config.json"

DEFAULT_BASE_URL = "https://acl-production.up.railway.app"


def _ensure_dir() -> None:
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def load() -> dict[str, Any]:
    if not CONFIG_FILE.exists():
        return {}
    return json.loads(CONFIG_FILE.read_text())


def save(data: dict[str, Any]) -> None:
    _ensure_dir()
    CONFIG_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
    CONFIG_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR)  # 600


def get(key: str, default: Any = None) -> Any:
    return load().get(key, default)


def set_key(key: str, value: Any) -> None:
    data = load()
    data[key] = value
    save(data)


def get_api_key() -> str | None:
    return get("api_key")


def get_base_url() -> str:
    return get("base_url", DEFAULT_BASE_URL)


# --- Convenience functions for init command ---


def load_config() -> dict[str, Any] | None:
    """Load config; return None if file doesn't exist."""
    if not CONFIG_FILE.exists():
        return None
    data = load()
    return data if data else None


def save_config(api_key: str, base_url: str, email: str) -> None:
    """Save full config after registration."""
    save({"api_key": api_key, "base_url": base_url, "email": email})


def require_api_key() -> str:
    """Return API key or raise with a helpful message."""
    key = get_api_key()
    if not key:
        from acl_cli.output import error
        error("Конфигурация не найдена. Сначала запустите: acl init")
        raise typer.Exit(1)
    return key
