from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Dict

import yaml

BASTION_CLOUD_URL = "https://bastion-ai-hub.replit.app"


def get_cloud_url() -> str:
    return os.environ.get("BASTION_CLOUD_URL", BASTION_CLOUD_URL)


def get_bastion_dir(base: str = ".") -> Path:
    return Path(base) / ".bastion"


def is_initialized(base: str = ".") -> bool:
    bastion_dir = get_bastion_dir(base)
    return bastion_dir.exists() and (bastion_dir / "config.yaml").exists()


def load_config(base: str = ".") -> Dict[str, Any]:
    config_path = get_bastion_dir(base) / "config.yaml"
    with open(config_path, "r") as f:
        return yaml.safe_load(f)


def save_config(config: Dict[str, Any], base: str = ".") -> None:
    bastion_dir = get_bastion_dir(base)
    bastion_dir.mkdir(parents=True, exist_ok=True)
    config_path = bastion_dir / "config.yaml"
    with open(config_path, "w") as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)
