#!/bin/bash

# Run All Integration Tests
# Executes all integration test suites and provides combined results

set -e

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

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

echo -e "${BLUE}🚀 Running All Wasot Integration Tests${NC}"
echo "========================================"
echo "Project root: $PROJECT_ROOT"
echo "Test directory: $SCRIPT_DIR"
echo ""

# Initialize counters
TOTAL_SUITES=0
PASSED_SUITES=0
FAILED_SUITES=0

# Function to run a test suite
run_test_suite() {
    local suite_name="$1"
    local script_path="$2"
    
    echo -e "\n${YELLOW}📋 Running $suite_name${NC}"
    echo "$(printf '=%.0s' {1..50})"
    
    TOTAL_SUITES=$((TOTAL_SUITES + 1))
    
    if [ ! -f "$script_path" ]; then
        echo -e "${RED}❌ Test script not found: $script_path${NC}"
        FAILED_SUITES=$((FAILED_SUITES + 1))
        return 1
    fi
    
    if [ ! -x "$script_path" ]; then
        echo -e "${YELLOW}⚠️  Making test script executable: $script_path${NC}"
        chmod +x "$script_path"
    fi
    
    # Run the test suite and capture exit code
    if "$script_path"; then
        echo -e "\n${GREEN}✅ $suite_name: PASSED${NC}"
        PASSED_SUITES=$((PASSED_SUITES + 1))
        return 0
    else
        echo -e "\n${RED}❌ $suite_name: FAILED${NC}"
        FAILED_SUITES=$((FAILED_SUITES + 1))
        return 1
    fi
}

# Build the project first
echo -e "${BLUE}🔨 Building project in release mode...${NC}"
cd "$PROJECT_ROOT"
if cargo build --release --quiet; then
    echo -e "${GREEN}✅ Build successful${NC}"
else
    echo -e "${RED}❌ Build failed - cannot run integration tests${NC}"
    exit 1
fi

# Run Memory Constraint Tests
run_test_suite "Memory Constraint Tests" "$SCRIPT_DIR/memory_constraint_tests.sh"

# Add more test suites here as they are created
# run_test_suite "Performance Tests" "$SCRIPT_DIR/performance_tests.sh"
# run_test_suite "Roundtrip Tests" "$SCRIPT_DIR/roundtrip_tests.sh"

# Final Results Summary
echo ""
echo -e "${BLUE}========================================"
echo "🏁 Integration Test Results Summary"
echo -e "========================================${NC}"

echo "Total test suites: $TOTAL_SUITES"
echo -e "Passed: ${GREEN}$PASSED_SUITES${NC}"
echo -e "Failed: ${RED}$FAILED_SUITES${NC}"

if [ $FAILED_SUITES -eq 0 ]; then
    echo -e "\n${GREEN}🎉 All integration test suites passed!${NC}"
    echo -e "${GREEN}✅ System is ready for production use${NC}"
    exit 0
else
    PASS_RATE=$(( (PASSED_SUITES * 100) / TOTAL_SUITES ))
    echo -e "\n${RED}❌ $FAILED_SUITES test suite(s) failed${NC}"
    echo -e "${YELLOW}📊 Pass rate: ${PASS_RATE}%${NC}"
    echo -e "${YELLOW}⚠️  Please review failed tests before deployment${NC}"
    exit 1
fi