# Copyright (C) 2026 GoodData Corporation

"""Runtime bootstrap helpers for the AIDA CLI."""

from __future__ import annotations

import os
import sys
from pathlib import Path


def maybe_setup_java_env() -> None:
    """Best-effort: add SDKMAN Java to PATH and set JAVA_HOME."""

    java_home = Path.home() / ".sdkman" / "candidates" / "java" / "current"
    java_bin = java_home / "bin"
    if java_bin.is_dir():
        os.environ["PATH"] = f"{java_bin}:{os.environ.get('PATH', '')}"
        os.environ.setdefault("JAVA_HOME", str(java_home))


def maybe_setup_codeartifact_token() -> None:
    """Best-effort: load CodeArtifact token for Gradle dependency resolution."""

    token_path = Path.home() / ".gradle" / ".codeartifact-token"
    if not token_path.is_file():
        return

    try:
        token = token_path.read_text(encoding="utf-8").strip()
    except Exception as exc:  # noqa: BLE001
        print(f"[aida-mcp] WARNING: Failed to read {token_path}: {exc}", file=sys.stderr)
        return

    if token:
        os.environ.setdefault("CODEARTIFACT_AUTH_TOKEN", token)


def run_stdio_server() -> None:
    """Run the MCP stdio server with runtime environment initialized."""

    maybe_setup_java_env()
    maybe_setup_codeartifact_token()
    from aida_mcp.server.__main__ import main as server_main

    server_main()
