"""Utility functions for Agent Berlin SDK."""

import os

from .session import load_session_config


def get_project_domain(config_path: str | None = None) -> str:
    """Get the project domain.

    Resolution order:
        1. PROJECT_DOMAIN environment variable
        2. ~/.agentberlin/config.json
        3. .agentberlin/config.json (CWD)
        4. Custom config_path (if provided)

    Args:
        config_path: Optional custom config file path.

    Returns:
        The project domain string.

    Raises:
        RuntimeError: If project domain is not found in env or config.
    """
    # First check environment variable
    domain = os.environ.get("PROJECT_DOMAIN")
    if domain:
        return domain

    # Try loading from config file
    config = load_session_config(config_path)
    domain = config.get("project_domain")
    if domain:
        return domain

    raise RuntimeError(
        "Project domain not found. Set PROJECT_DOMAIN environment variable "
        "or run 'agentberlin configure --token <token> --domain <domain>' to save credentials."
    )
