"""Config management — reads/writes .quark/config.toml in the current project."""
from __future__ import annotations

import os
import toml
from pathlib import Path

CONFIG_DIR  = ".quark"
CONFIG_FILE = "config.toml"
DEFAULT_URL = "https://quark-ai.cordee.ovh"


def _config_path() -> Path:
    return Path(CONFIG_DIR) / CONFIG_FILE


def config_exists() -> bool:
    return _config_path().exists()


def load() -> dict:
    if not config_exists():
        raise FileNotFoundError(
            "No .quark/config.toml found. Run `quark init` first."
        )
    return toml.load(_config_path())


def save(cfg: dict) -> None:
    Path(CONFIG_DIR).mkdir(exist_ok=True)
    with open(_config_path(), "w") as f:
        toml.dump(cfg, f)


def get(key: str, default=None):
    try:
        return load().get(key, default)
    except FileNotFoundError:
        return default


# Env override — QUARK_TOKEN and QUARK_URL take priority over config file
def token() -> str | None:
    return os.getenv("QUARK_TOKEN") or get("token")


def api_url() -> str:
    return os.getenv("QUARK_API_URL") or get("api_url", DEFAULT_URL)
