"""Configuration management — loads/saves ~/.turumba/config.yaml."""

from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml

TURUMBA_DIR = Path.home() / ".turumba"
CONFIG_FILE = TURUMBA_DIR / "config.yaml"

DEFAULTS: dict[str, Any] = {
    "gateway_url": "https://api.dev.turumba.net",
    "default_account_id": None,
    "default_output": "table",
}


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


def load_config() -> dict[str, Any]:
    """Load config from disk, merged with defaults."""
    config = dict(DEFAULTS)
    if CONFIG_FILE.exists():
        with CONFIG_FILE.open() as f:
            saved = yaml.safe_load(f) or {}
        config.update(saved)
    return config


def save_config(config: dict[str, Any]) -> None:
    """Write config to disk."""
    _ensure_dir()
    with CONFIG_FILE.open("w") as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)


def get_value(key: str) -> Any:
    """Get a single config value."""
    config = load_config()
    return config.get(key)


def set_value(key: str, value: Any) -> None:
    """Set a single config value and persist."""
    config = load_config()
    config[key] = value
    save_config(config)
