#!/bin/bash

# Coherence MCP Python Server Wrapper
# This script ensures the Python environment is properly set up

# Get the directory of this script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COHERENCE_ROOT="$( cd "$SCRIPT_DIR/../../.." && pwd )"

# Export environment variables
export GATEWAY_URL="${COHERENCE_GATEWAY_URL:-${GATEWAY_URL:-http://localhost:8000}}"
export JWT_SECRET="${COHERENCE_JWT_SECRET:-${JWT_SECRET:-55c121aa48dc1b79e3c04c805aabd2fe7646253ab6edd1c61894f8146ce1ed17}}"
export LOG_LEVEL="${COHERENCE_LOG_LEVEL:-${LOG_LEVEL:-INFO}}"

# Handle bundle parameter
if [ "$1" = "--bundle" ] && [ -n "$2" ]; then
    export BUNDLE_NAME="$2"
fi

# Change to coherence root directory
cd "$COHERENCE_ROOT"

# Check if we're in a Poetry environment
if [ -f "pyproject.toml" ] && command -v poetry &> /dev/null; then
    echo "Using Poetry environment..." >&2
    exec poetry run python -m mcp_adapter.server
elif [ -f ".venv/bin/python" ]; then
    echo "Using local .venv..." >&2
    exec .venv/bin/python -m mcp_adapter.server
else
    echo "Using system Python..." >&2
    # Try to use python3 with user site-packages
    export PYTHONPATH="$COHERENCE_ROOT:$PYTHONPATH"
    exec python3 -m mcp_adapter.server
fi