"""Configuration management for Anor CLI"""
import json
import os
from pathlib import Path
from typing import Optional

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

DEFAULT_API_URL = "https://anorcloud.com"


def ensure_config_dir():
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


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


def save_config(config: dict):
    ensure_config_dir()
    CONFIG_FILE.write_text(json.dumps(config, indent=2))


def get_api_url() -> str:
    config = load_config()
    return config.get("api_url") or os.environ.get("ANOR_API_URL") or DEFAULT_API_URL


def get_api_key() -> Optional[str]:
    config = load_config()
    return config.get("api_key") or os.environ.get("ANOR_API_KEY")


def set_api_key(api_key: str):
    config = load_config()
    config["api_key"] = api_key
    save_config(config)


def set_api_url(api_url: str):
    config = load_config()
    config["api_url"] = api_url
    save_config(config)


def clear_credentials():
    config = load_config()
    config.pop("api_key", None)
    save_config(config)


def is_logged_in() -> bool:
    return get_api_key() is not None
