"""Auth and config management for ~/.corpo/config.json.

Separate from the TOML-based config.py which handles governance settings.
This module handles API key auth and user preferences.
"""

import json
import os
from pathlib import Path

CONFIG_PATH = Path("~/.corpo/config.json").expanduser()

AUTH_DEFAULTS = {
    "api_url": "https://api.corpo.dev/api/v1",
    "api_key": "",
    "account_id": "",
    "default_output": "table",
    "human": False,
}

VALID_KEYS = set(AUTH_DEFAULTS.keys())


def load_auth_config() -> dict:
    """Load ~/.corpo/config.json, returning defaults for missing keys."""
    cfg = dict(AUTH_DEFAULTS)
    if CONFIG_PATH.exists():
        try:
            with open(CONFIG_PATH) as f:
                data = json.load(f)
            cfg.update({k: v for k, v in data.items() if k in VALID_KEYS})
        except (json.JSONDecodeError, OSError):
            pass
    return cfg


def save_auth_config(cfg: dict) -> None:
    """Write config to ~/.corpo/config.json."""
    CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
    with open(CONFIG_PATH, "w") as f:
        json.dump(cfg, f, indent=2)
        f.write("\n")


def get_api_key(cfg: dict | None = None) -> str:
    """Resolve API key: CORPO_API_KEY env var > config file."""
    env_key = os.environ.get("CORPO_API_KEY", "")
    if env_key:
        return env_key
    if cfg is None:
        cfg = load_auth_config()
    return cfg.get("api_key", "")


def require_api_key(cfg: dict | None = None) -> str:
    """Get API key or exit with a clear error."""
    key = get_api_key(cfg)
    if not key:
        from corpo.output import error
        error(
            "No API key configured",
            hint="Run `corpo register` first or set CORPO_API_KEY",
        )
    return key


def get_api_url(cfg: dict | None = None) -> str:
    """Resolve API URL: CORPO_API_URL env > config > default."""
    env_url = os.environ.get("CORPO_API_URL", "")
    if env_url:
        return env_url
    if cfg is None:
        cfg = load_auth_config()
    return cfg.get("api_url", AUTH_DEFAULTS["api_url"])
