"""Manages ~/.loony/config.yaml — environments, credentials, current context."""

import os
from pathlib import Path
from typing import Any

import yaml

CONFIG_DIR = Path.home() / ".loony"
CONFIG_FILE = CONFIG_DIR / "config.yaml"

DEFAULTS = {
    "staging": {
        "endpoint": "https://control-plane-staging-f80a.up.railway.app",
        "workos_client_id": "client_01KM7YSX929XY123SB97D5VP2T",
    },
    "production": {
        "endpoint": "",
        "workos_client_id": "",
    },
}


def _ensure_dir() -> None:
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_DIR.chmod(0o700)


def load() -> dict[str, Any]:
    if not CONFIG_FILE.exists():
        return {"current": "staging", "environments": {}}
    with open(CONFIG_FILE) as f:
        result: dict[str, Any] = yaml.safe_load(f) or {"current": "staging", "environments": {}}
        return result


def save(config: dict[str, Any]) -> None:
    _ensure_dir()
    with open(CONFIG_FILE, "w") as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)
    CONFIG_FILE.chmod(0o600)


def get_current_env() -> str:
    result: str = os.environ.get("LOONY_ENV") or str(load().get("current", "staging"))
    return result


def get_env_config(env: str | None = None) -> dict[str, Any]:
    env = env or get_current_env()
    config = load()
    env_config = config.get("environments", {}).get(env, {})
    defaults = DEFAULTS.get(env, {})
    return {**defaults, **env_config}


def set_current_env(env: str) -> None:
    config = load()
    config["current"] = env
    save(config)


def save_credentials(env: str, credentials: dict[str, Any]) -> None:
    config = load()
    if "environments" not in config:
        config["environments"] = {}
    if env not in config["environments"]:
        config["environments"][env] = {}
    config["environments"][env].update(credentials)
    config["current"] = env
    save(config)


def clear_credentials(env: str) -> None:
    config = load()
    envs = config.get("environments", {})
    if env in envs:
        envs[env].pop("access_token", None)
        envs[env].pop("refresh_token", None)
        envs[env].pop("user_id", None)
        envs[env].pop("email", None)
    save(config)
