#!/bin/bash
set -e

echo "=========================================="
echo "    CORTEX HUB INTEGRATION TESTS SETUP    "
echo "=========================================="

# 1. Provide an .env if missing
if [ ! -f ".env" ]; then
    echo "Creating default .env for testing..."
    cat <<EOF > .env
CORTEX_ADMIN_PASSWORD=admin
SECRET_KEY=integration-secret-key-123
SUPER_ADMINS=admin@jerxie.com
GEMINI_API_KEY=your_gemini_api_key
EOF
    echo "Please edit the .env file with your actual GEMINI_API_KEY and run this script again."
    exit 1
fi

# Load variables to use them in this script
export $(grep -v '^#' .env | xargs)

# Parse flags
NO_REBUILD=false
if [[ "$*" == *"--no-rebuild"* ]]; then
    NO_REBUILD=true
fi

# Check if docker daemon is reachable (i.e., not inside DevContainer without DIND) or if specifically skipped
DOCKER_AVAILABLE=false
if docker info >/dev/null 2>&1 && [ "$SKIP_DOCKER_NODES" != "true" ]; then
    DOCKER_AVAILABLE=true
    export SKIP_DOCKER_NODES=false
else
    echo "Docker skipping or not reachable (likely Native mode). Switching to Native Python mode..."
    export SKIP_DOCKER_NODES=true
    export SYNC_TEST_BASE_URL="http://127.0.0.1:8000/api/v1"
fi

if [ "$NO_REBUILD" = true ] && [ "$IS_RUNNING" = true ]; then
    echo "Service is already running and --no-rebuild flag provided."
    echo "Skipping rebuild and starting tests directly..."
else
    if [ "$DOCKER_AVAILABLE" = true ]; then
        # 2. Clean start: purge the database / volumes
        echo "Purging database and old containers..."
        docker compose down -v --remove-orphans
        docker kill test-node-1 test-node-2 2>/dev/null || true
        docker rm test-node-1 test-node-2 2>/dev/null || true

        # 3. Build & start the Hub stack
        echo "Starting AI Hub mesh..."
        mkdir -p data
        docker compose build ai-hub ai-frontend
        docker compose up -d

        # Wait for healthy
        echo "Waiting for AI Hub to be ready..."
        sleep 5
        until curl -I -s http://localhost:8002/api/v1/users/login/local | grep -q "405"; do
            echo "Waiting for AI Hub Backend..."
            sleep 2
        done
        sleep 3
        echo "AI Hub Backend is online."
    else
        # Start AI Hub Backend natively via uvicorn
        echo "Starting AI Hub natively in the background..."
        export DATABASE_URL="sqlite:///./data/ai-hub-test.db"
        export ENVIRONMENT="development"
        export PATH_PREFIX="/api/v1"
        # Purge local test database
        rm -f ai-hub/test.db
        mkdir -p ai-hub/data
        
        pkill -f uvicorn || true
        pkill -f agent_node.main || true
        sleep 1
        
        if [ -d "ai-hub" ]; then
            cd ai-hub
        elif [ -d "/app/ai-hub" ]; then
            cd /app/ai-hub
        fi
        DATA_DIR=./data DATABASE_URL=sqlite:///./test.db AGENT_NODE_SRC_DIR=../agent-node SKILLS_SRC_DIR=../skills uvicorn app.main:app --host 0.0.0.0 --port 8000 > native_hub.log 2>&1 &
        HUB_PID=$!
        cd - > /dev/null
        
        # Wait for healthy
        echo "Waiting for AI Hub to be ready..."
        sleep 2
        until curl -I -s http://localhost:8000/api/v1/users/login/local | grep -q "405"; do
            echo "Waiting for AI Hub Backend natively..."
            sleep 2
        done
        sleep 3
        echo "AI Hub Backend is online."
    fi
fi

# 4. User setup via Pytest fixtures
echo "=========================================="
echo "    EXECUTING E2E INTEGRATION SUITE       "
echo "=========================================="
if [ "$NATIVE" = 1 ]; then
    export SYNC_TEST_BASE_URL="http://127.0.0.1:8000/api/v1"
    export TEST_HUB_URL="http://127.0.0.1:8000"
    export TEST_GRPC_ENDPOINT="127.0.0.1:50051"
fi
source /tmp/venv/bin/activate || echo "No venv found, hoping pytest is in global PATH."

TEST_TARGETS=()
for arg in "$@"; do
    if [[ "$arg" != "--no-rebuild" ]]; then
        TEST_TARGETS+=("$arg")
    fi
done

if [ ${#TEST_TARGETS[@]} -eq 0 ]; then
    TEST_TARGETS=("ai-hub/integration_tests/")
fi

pytest "${TEST_TARGETS[@]}" -v

if [ "$NO_REBUILD" = false ] || [ "$IS_RUNNING" = false ]; then
    echo "=========================================="
    echo "    TEARING DOWN INTEGRATION ENVIRONMENT  "
    if [ "$DOCKER_AVAILABLE" = true ]; then
        docker compose down -v
    else
        kill $HUB_PID || true
    fi
    echo "Done!"
else
    echo "=========================================="
    echo " SKIPPING TEARDOWN DUE TO --no-rebuild    "
    echo "=========================================="
    echo "Done!"
fi
