#!/bin/bash
# Quick Start Script for Testing Go MCA SDK in Google Cloud Workbench

set -e

echo "╔════════════════════════════════════════════════════════════╗"
echo "║      Go MCA SDK - Quick Start Test & Validation           ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Track results
TOTAL_STEPS=8
CURRENT_STEP=0
FAILED_STEPS=0

step() {
    ((CURRENT_STEP++))
    echo ""
    echo -e "${BLUE}[Step $CURRENT_STEP/$TOTAL_STEPS]${NC} $1"
    echo "────────────────────────────────────────────────────────"
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
    ((FAILED_STEPS++))
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Step 1: Check Prerequisites
step "Checking Prerequisites"

# Check Go version
if command -v go &> /dev/null; then
    GO_VERSION=$(go version | awk '{print $3}')
    success "Go installed: $GO_VERSION"
else
    error "Go is not installed. Please install Go 1.21+"
    exit 1
fi

# Check Docker
if command -v docker &> /dev/null; then
    DOCKER_VERSION=$(docker --version | awk '{print $3}' | tr -d ',')
    success "Docker installed: $DOCKER_VERSION"
else
    error "Docker is not installed"
    exit 1
fi

# Check Docker Compose
if command -v docker-compose &> /dev/null; then
    success "Docker Compose installed"
else
    error "Docker Compose is not installed"
    exit 1
fi

# Step 2: Download Dependencies
step "Downloading Go Dependencies"

export GOPROXY=https://proxy.golang.org,direct
export GOSUMDB=sum.golang.org

if go mod download 2>&1 | tee /tmp/go-download.log; then
    if go mod tidy 2>&1 | tee -a /tmp/go-download.log; then
        success "Dependencies downloaded"
    else
        warning "go mod tidy had issues (may be cert-related, continuing...)"
        # Try with insecure mode
        export GOINSECURE='*.golang.org,github.com'
        go mod download || true
    fi
else
    warning "Dependency download had issues (cert-related, may affect tests)"
fi

# Step 3: Run Unit Tests
step "Running Unit Tests"

echo "Running all tests..."
if go test -v ./... 2>&1 | tee /tmp/go-test.log; then
    TEST_COUNT=$(grep -c "PASS:" /tmp/go-test.log || echo "0")
    success "All tests passed ($TEST_COUNT tests)"
else
    error "Some tests failed"
    echo "See /tmp/go-test.log for details"
fi

# Step 4: Run Race Detection
step "Running Race Detector"

echo "Checking for race conditions..."
if go test -race ./... 2>&1 | tee /tmp/go-race.log; then
    success "No race conditions detected"
else
    error "Race conditions found!"
    echo "See /tmp/go-race.log for details"
    warning "This is critical - fix before production!"
fi

# Step 5: Check Test Coverage
step "Checking Test Coverage"

COVERAGE=$(go test -cover ./... 2>&1 | grep coverage | awk '{print $2}' | tr -d '%')
if [ ! -z "$COVERAGE" ]; then
    if (( $(echo "$COVERAGE >= 85" | bc -l) )); then
        success "Test coverage: ${COVERAGE}% (target: ≥85%)"
    else
        warning "Test coverage: ${COVERAGE}% (target: ≥85%)"
    fi
else
    warning "Could not determine coverage"
fi

# Step 6: Start OTel Collector
step "Starting OpenTelemetry Collector"

cd ../..  # Go to mca-prototype directory

if docker-compose ps | grep -q "otel-collector.*Up"; then
    success "OTel Collector already running"
else
    echo "Starting OTel Collector..."
    if docker-compose up -d otel-collector 2>&1 | tee /tmp/docker-compose.log; then
        sleep 3
        if curl -s http://localhost:13133/ > /dev/null 2>&1; then
            success "OTel Collector started and healthy"
        else
            warning "OTel Collector started but health check failed"
        fi
    else
        error "Failed to start OTel Collector"
        echo "See /tmp/docker-compose.log for details"
    fi
fi

# Step 7: Run Example Application
step "Running Example Application"

cd sdk-examples/internal-model-go

echo "Executing example..."
if timeout 30 go run main.go 2>&1 | tee /tmp/go-example.log; then
    PREDICTIONS=$(grep -c "Recorded prediction" /tmp/go-example.log || echo "0")
    success "Example completed successfully ($PREDICTIONS predictions recorded)"
else
    error "Example failed or timed out"
    echo "See /tmp/go-example.log for details"
fi

# Step 8: Validate Telemetry
step "Validating Telemetry Data"

cd ../..  # Back to mca-prototype

sleep 2  # Give collector time to process

METRIC_COUNT=$(docker-compose logs otel-collector 2>/dev/null | grep -c "model.predictions_total" || echo "0")
TRACE_COUNT=$(docker-compose logs otel-collector 2>/dev/null | grep -c "record_prediction" || echo "0")

if [ "$METRIC_COUNT" -gt "0" ]; then
    success "Metrics received by collector ($METRIC_COUNT entries)"
else
    warning "No metrics found in collector logs"
fi

if [ "$TRACE_COUNT" -gt "0" ]; then
    success "Traces received by collector ($TRACE_COUNT entries)"
else
    warning "No traces found in collector logs"
fi

# Final Summary
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                    TEST SUMMARY                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

if [ $FAILED_STEPS -eq 0 ]; then
    echo -e "${GREEN}✅ ALL TESTS PASSED!${NC}"
    echo ""
    echo "The Go MCA SDK is working correctly and ready for use."
    echo ""
    echo "Next steps:"
    echo "  1. Review test logs in /tmp/go-*.log"
    echo "  2. Check OTel Collector: docker-compose logs otel-collector"
    echo "  3. View detailed testing guide: cat TESTING.md"
    echo "  4. Run benchmarks: go test -bench=. ./..."
    exit 0
else
    echo -e "${RED}❌ $FAILED_STEPS STEP(S) FAILED${NC}"
    echo ""
    echo "Please review the errors above and check log files:"
    echo "  - /tmp/go-test.log (unit tests)"
    echo "  - /tmp/go-race.log (race detection)"
    echo "  - /tmp/go-example.log (example output)"
    echo "  - /tmp/docker-compose.log (docker logs)"
    echo ""
    echo "For detailed troubleshooting, see: TESTING.md"
    exit 1
fi
