"""
_base.py — Shared utilities for pipeline modules.

Each pipeline module imports mcp_servers() and event_env() from here.
"""
from __future__ import annotations

import os
import pathlib
import sys

from ..models import WebhookEvent

_IS_WINDOWS = sys.platform == "win32"
# project_root/.venv/bin  (5 parents up from this file inside src/stlc_agents/webhook_orchestrator/pipelines/)
_BIN_DIR = (
    pathlib.Path(__file__).parent.parent.parent.parent.parent.resolve()
    / ".venv"
    / ("Scripts" if _IS_WINDOWS else "bin")
)
_EXT = ".exe" if _IS_WINDOWS else ""


def mcp_servers(*names: str) -> dict:
    """Build an MCP config dict containing only the named server executables."""
    return {
        "mcpServers": {
            name: {"command": str(_BIN_DIR / f"{name}{_EXT}"), "args": []}
            for name in names
        }
    }


def event_env(event: WebhookEvent) -> dict[str, str]:
    """Merge event-level credentials into a copy of os.environ for subprocess isolation."""
    env: dict[str, str] = dict(os.environ)
    if event.organization_url:
        env["ADO_ORGANIZATION_URL"] = event.organization_url
    if event.project_name:
        env["ADO_PROJECT_NAME"] = event.project_name
    if event.cloud_id:
        env["JIRA_CLOUD_ID"] = event.cloud_id
    if event.llm_provider:
        env["LLM_PROVIDER"] = event.llm_provider
    if event.llm_model:
        env["LLM_MODEL"] = event.llm_model
    if event.llm_api_key:
        env["LLM_API_KEY"] = event.llm_api_key
    if event.llm_base_url:
        env["LLM_BASE_URL"] = event.llm_base_url
    if event.app_base_url:
        env["APP_BASE_URL"] = event.app_base_url
    if event.app_username:
        env["APP_USERNAME"] = event.app_username
    if event.app_password:
        env["APP_PASSWORD"] = event.app_password
    return env
