# Copyright (C) 2026 GoodData Corporation

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

from __future__ import annotations

import os
import sys
from pathlib import Path

from aida_mcp.server.mcp_install_common import DEFAULT_HTTP_PORT


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.app_instance import mcp
    from aida_mcp.server.registry import register_all

    register_all(mcp)
    mcp.run()


def run_streamable_http_server(
    *,
    host: str | None = None,
    port: int | None = None,
    path: str | None = None,
    workspace_root: str | None = None,
) -> None:
    """Run the MCP server in Streamable HTTP mode."""

    maybe_setup_java_env()
    maybe_setup_codeartifact_token()

    if workspace_root:
        resolved_root = Path(workspace_root).expanduser().resolve()
        os.environ["AIDA_WORKSPACE_ROOT"] = str(resolved_root)
        os.chdir(resolved_root)

    from aida_mcp.server.app_instance import mcp
    from aida_mcp.server.registry import register_all

    register_all(mcp)
    if host:
        mcp.settings.host = host
    mcp.settings.port = DEFAULT_HTTP_PORT if port is None else port
    if path:
        mcp.settings.streamable_http_path = path

    print(
        f"[aida-mcp] serving Streamable HTTP on http://{mcp.settings.host}:{mcp.settings.port}"
        f"{mcp.settings.streamable_http_path}",
        file=sys.stderr,
    )
    try:
        mcp.run(transport="streamable-http")
    except KeyboardInterrupt:
        print("[aida-mcp] Streamable HTTP server stopped.", file=sys.stderr)
