"""Configuration management for GPAI CLI."""

import json
import os
from pathlib import Path

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

DEFAULT_API_URL = "https://api-dev.gpai.app"


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


def load_config() -> dict:
    if not CONFIG_FILE.exists():
        return {}
    return json.loads(CONFIG_FILE.read_text())


def save_config(config: dict) -> None:
    _ensure_config_dir()
    CONFIG_FILE.write_text(json.dumps(config, indent=2))


def get_token() -> str | None:
    return os.environ.get("GPAI_API_KEY") or load_config().get("token")


def get_api_url() -> str:
    return os.environ.get("GPAI_API_URL") or load_config().get("api_url", DEFAULT_API_URL)
