"""
Configuration management — loads/saves ~/.machins/config.json.
"""

from __future__ import annotations

import json
import os
from pathlib import Path

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


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


def save_config(data: dict) -> None:
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(json.dumps(data, indent=2) + "\n")
    os.chmod(CONFIG_FILE, 0o600)


def get_api_key() -> str | None:
    return os.environ.get("MACHINS_API_KEY") or load_config().get("api_key")


def get_base_url() -> str:
    return (
        os.environ.get("MACHINS_BASE_URL")
        or load_config().get("base_url")
        or "https://machins.co/api/v1"
    )
