#!/bin/bash
# Integration test runner for Kubernetes deployment
# Requires: kubectl configured, test cluster with monitoring namespace

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "=== OpenTelemetry Collector K8s Integration Tests ==="
echo ""

# Check prerequisites
echo "Checking prerequisites..."

if ! command -v kubectl &> /dev/null; then
    echo "ERROR: kubectl not found. Please install kubectl."
    exit 1
fi

if ! kubectl cluster-info &> /dev/null; then
    echo "ERROR: kubectl not configured or cluster not accessible."
    exit 1
fi

if ! kubectl get namespace monitoring &> /dev/null; then
    echo "ERROR: Namespace 'monitoring' does not exist."
    echo "Create it with: kubectl create namespace monitoring"
    exit 1
fi

echo "✓ kubectl configured"
echo "✓ Cluster accessible"
echo "✓ Namespace 'monitoring' exists"
echo ""

# Check if collector is deployed
echo "Checking collector deployment..."

if ! kubectl get statefulset -n monitoring otel-collector &> /dev/null; then
    echo "ERROR: StatefulSet 'otel-collector' not found in namespace 'monitoring'."
    echo "Deploy it with: kubectl apply -f k8s/"
    exit 1
fi

READY_PODS=$(kubectl get statefulset -n monitoring otel-collector -o jsonpath='{.status.readyReplicas}')
DESIRED_PODS=$(kubectl get statefulset -n monitoring otel-collector -o jsonpath='{.spec.replicas}')

echo "✓ StatefulSet 'otel-collector' found"
echo "  Ready pods: $READY_PODS / $DESIRED_PODS"

if [ "$READY_PODS" -lt 3 ]; then
    echo "WARNING: Less than 3 pods ready. Some tests may fail."
fi

echo ""

# Install Python dependencies
echo "Installing test dependencies..."
cd "$PROJECT_ROOT"

if [ ! -d "venv" ]; then
    echo "Creating virtual environment..."
    python3 -m venv venv
fi

source venv/bin/activate 2>/dev/null || source venv/Scripts/activate 2>/dev/null

pip install -q pytest requests

echo "✓ Dependencies installed"
echo ""

# Run tests
echo "Running integration tests..."
echo ""

pytest tests/integration/test_k8s_deployment.py \
    -v \
    --tb=short \
    --color=yes \
    --durations=10

TEST_EXIT_CODE=$?

echo ""
if [ $TEST_EXIT_CODE -eq 0 ]; then
    echo "=== ✓ All tests passed ==="
else
    echo "=== ✗ Some tests failed ==="
    echo ""
    echo "Troubleshooting:"
    echo "1. Check pod status: kubectl get pods -n monitoring -l app=otel-collector"
    echo "2. Check pod logs: kubectl logs -n monitoring otel-collector-0"
    echo "3. Check events: kubectl get events -n monitoring --sort-by='.lastTimestamp'"
    echo "4. See deployment guide: k8s/DEPLOYMENT.md"
fi

exit $TEST_EXIT_CODE
