"""
Shared configuration for Nexus examples.

Loads settings from environment variables (or .env file).
All examples import from here instead of hardcoding credentials.

Usage:
    from _config import get_model_config, get_embedding_config
"""

from __future__ import annotations

import os
import sys
from pathlib import Path


def _load_dotenv() -> None:
    """Load .env from the examples directory if it exists."""
    env_file = Path(__file__).parent / ".env"
    if not env_file.exists():
        return
    for line in env_file.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if "=" in line:
            key, _, value = line.partition("=")
            key, value = key.strip(), value.strip()
            # Don't override existing env vars
            if key not in os.environ:
                os.environ[key] = value


# Auto-load on import
_load_dotenv()


def _require(var: str) -> str:
    """Get a required environment variable, or exit with a helpful message."""
    value = os.environ.get(var)
    if not value or value.startswith("your-"):
        print(
            f"Error: environment variable {var} is not set.\n"
            f"Please copy examples/.env.example to examples/.env and fill in your values.\n"
            f"  cp examples/.env.example examples/.env",
            file=sys.stderr,
        )
        sys.exit(1)
    return value


def get_model_config() -> dict:
    """Return model kwargs for Team() / _create_provider()."""
    return {
        "model": _require("NEXUS_MODEL"),
        "base_url": _require("NEXUS_BASE_URL"),
        "api_key": _require("NEXUS_API_KEY"),
        "provider": "litellm",
    }


def get_embedding_config() -> dict:
    """Return embedding kwargs for Team() in Adaptive mode."""
    return {
        "embedding_model": _require("NEXUS_EMBEDDING_MODEL"),
        "embedding_api_key": _require("NEXUS_EMBEDDING_API_KEY"),
        "embedding_base_url": _require("NEXUS_EMBEDDING_BASE_URL"),
    }
