"""Global iEvo config — ~/.ievo/config.json (plaintext, non-sensitive)."""

from __future__ import annotations

import json
from pathlib import Path

DEFAULT_CONFIG: dict[str, object] = {
    "default_model": "sonnet",
    "marketplace_url": "https://github.com/ievo-ai/marketplace",
    "auto_update_registry": True,
    "github_auth": None,  # "gh_cli" | "pat" | None
    "claude_auth": None,  # "cli" | "env" | None
    "telemetry": None,  # True | False | None (not asked yet)
}


def _config_path(home: Path) -> Path:
    return home / "config.json"


def load_global_config(home: Path) -> dict[str, object]:
    """Load config.json, creating with defaults if missing."""
    path = _config_path(home)
    if not path.exists():
        save_global_config(home, dict(DEFAULT_CONFIG))
        return dict(DEFAULT_CONFIG)
    data = json.loads(path.read_text())
    # Merge with defaults for any missing keys
    merged = dict(DEFAULT_CONFIG)
    merged.update(data)
    return merged


def save_global_config(home: Path, config: dict[str, object]) -> None:
    """Write config.json."""
    path = _config_path(home)
    path.write_text(json.dumps(config, indent=2) + "\n")


def get_config(home: Path, key: str) -> object:
    """Get a config value."""
    config = load_global_config(home)
    return config.get(key)


def set_config(home: Path, key: str, value: object) -> None:
    """Set a config value."""
    config = load_global_config(home)
    config[key] = value
    save_global_config(home, config)
