#!/bin/bash

# Comprehensive test validation for Trip With Us

echo "=== Test Validation ==="

# Configuration
MIN_COVERAGE=80
MIN_E2E_COVERAGE=70
TIMEOUT=300  # 5 minutes

# Create test results directory
mkdir -p ../state/test-reports

# Unit test validation
echo "🧪 Running unit tests..."
unit_start=$(date +%s)

if timeout $TIMEOUT cd ../.. && npm run test -- --coverage --verbose --json > meta-agent/state/test-reports/unit-test-results.json 2>&1; then
    unit_end=$(date +%s)
    unit_duration=$((unit_end - unit_start))
    
    echo "✅ Unit tests completed in ${unit_duration}s"
    
    # Parse test results
    if [ -f "../state/test-reports/unit-test-results.json" ]; then
        # Extract key metrics (this depends on your Jest configuration)
        test_results=$(cat ../state/test-reports/unit-test-results.json)
        
        # For Jest JSON output, you might parse like this:
        total_tests=$(echo "$test_results" | jq '.numTotalTests // 0' 2>/dev/null || echo "0")
        passed_tests=$(echo "$test_results" | jq '.numPassedTests // 0' 2>/dev/null || echo "0")
        failed_tests=$(echo "$test_results" | jq '.numFailedTests // 0' 2>/dev/null || echo "0")
        
        echo "📊 Unit Test Results:"
        echo "  Total: $total_tests"
        echo "  Passed: $passed_tests"
        echo "  Failed: $failed_tests"
        
        if [ "$failed_tests" -eq 0 ]; then
            echo "✅ All unit tests passing"
        else
            echo "❌ $failed_tests unit tests failing"
            exit 1
        fi
    fi
else
    echo "❌ Unit tests failed or timed out"
    exit 1
fi

# Coverage validation
echo "🔍 Analyzing test coverage..."
if [ -f "../../coverage/coverage-summary.json" ]; then
    coverage_data=$(cat ../../coverage/coverage-summary.json)
    
    # Extract coverage metrics
    line_coverage=$(echo "$coverage_data" | jq '.total.lines.pct // 0' 2>/dev/null || echo "0")
    function_coverage=$(echo "$coverage_data" | jq '.total.functions.pct // 0' 2>/dev/null || echo "0")
    branch_coverage=$(echo "$coverage_data" | jq '.total.branches.pct // 0' 2>/dev/null || echo "0")
    statement_coverage=$(echo "$coverage_data" | jq '.total.statements.pct // 0' 2>/dev/null || echo "0")
    
    echo "📊 Coverage Results:"
    echo "  Lines: ${line_coverage}%"
    echo "  Functions: ${function_coverage}%"
    echo "  Branches: ${branch_coverage}%"
    echo "  Statements: ${statement_coverage}%"
    
    # Check against thresholds
    line_coverage_int=${line_coverage%.*}
    if [ "$line_coverage_int" -ge "$MIN_COVERAGE" ]; then
        echo "✅ Line coverage meets threshold (${line_coverage}% ≥ ${MIN_COVERAGE}%)"
    else
        echo "❌ Line coverage below threshold (${line_coverage}% < ${MIN_COVERAGE}%)"
        
        # Show files with low coverage
        echo "📉 Files with low coverage:"
        echo "$coverage_data" | jq -r '.[] | select(.lines.pct < 80) | "\(.lines.pct)% - \(input_filename // "unknown")"' 2>/dev/null | head -10
        
        exit 1
    fi
else
    echo "⚠️  Coverage report not found"
fi

# Component test validation
echo "🧩 Validating component tests..."
component_files=$(find ../../src/components -name "*.tsx" 2>/dev/null | wc -l)
test_files=$(find ../../src/components -name "*.test.*" -o -name "*.spec.*" 2>/dev/null | wc -l)

if [ "$component_files" -gt 0 ]; then
    test_ratio=$((test_files * 100 / component_files))
    echo "📊 Component Test Coverage: $test_ratio% ($test_files/$component_files)"
    
    if [ "$test_ratio" -ge 70 ]; then
        echo "✅ Good component test coverage"
    else
        echo "⚠️  Low component test coverage"
        
        # Find components without tests
        echo "📝 Components without tests:"
        for component in $(find ../../src/components -name "*.tsx" | head -10); do
            component_name=$(basename "$component" .tsx)
            component_dir=$(dirname "$component")
            
            if [ ! -f "$component_dir/${component_name}.test.tsx" ] && [ ! -f "$component_dir/${component_name}.spec.tsx" ]; then
                echo "  - $component"
            fi
        done
    fi
else
    echo "⚠️  No React components found"
fi

# E2E test validation (if available)
if [ -f "../../package.json" ] && grep -q "test:e2e" ../../package.json; then
    echo "🎭 Running E2E tests..."
    e2e_start=$(date +%s)
    
    if timeout $((TIMEOUT * 2)) cd ../.. && npm run test:e2e > meta-agent/state/test-reports/e2e-results.txt 2>&1; then
        e2e_end=$(date +%s)
        e2e_duration=$((e2e_end - e2e_start))
        
        echo "✅ E2E tests completed in ${e2e_duration}s"
        
        # Parse Playwright results
        e2e_results=$(cat ../state/test-reports/e2e-results.txt)
        passed_e2e=$(echo "$e2e_results" | grep -o '[0-9]\+ passed' | grep -o '[0-9]\+' || echo "0")
        failed_e2e=$(echo "$e2e_results" | grep -o '[0-9]\+ failed' | grep -o '[0-9]\+' || echo "0")
        
        echo "📊 E2E Test Results:"
        echo "  Passed: $passed_e2e"
        echo "  Failed: $failed_e2e"
        
        if [ "$failed_e2e" -eq 0 ]; then
            echo "✅ All E2E tests passing"
        else
            echo "❌ $failed_e2e E2E tests failing"
            echo "📋 E2E failures:"
            echo "$e2e_results" | grep -A 5 -B 5 "FAIL\|✘"
            exit 1
        fi
    else
        echo "❌ E2E tests failed or timed out"
        echo "📋 E2E error output:"
        tail -20 ../state/test-reports/e2e-results.txt
        exit 1
    fi
else
    echo "⚠️  E2E tests not configured"
fi

# Test performance analysis
echo "⚡ Analyzing test performance..."

# Check for slow tests
if [ -f "../state/test-reports/unit-test-results.json" ]; then
    slow_tests=$(echo "$test_results" | jq '.testResults[] | select(.perfStats.runtime > 5000) | {name: .name, runtime: .perfStats.runtime}' 2>/dev/null)
    
    if [ -n "$slow_tests" ] && [ "$slow_tests" != "null" ]; then
        echo "🐌 Slow tests detected (>5s):"
        echo "$slow_tests" | jq -r '"\(.runtime)ms - \(.name)"' 2>/dev/null
    else
        echo "✅ No slow tests detected"
    fi
fi

# Generate comprehensive test report
cat > ../state/test-validation-report.json << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "unit_tests": {
    "total": ${total_tests:-0},
    "passed": ${passed_tests:-0},
    "failed": ${failed_tests:-0},
    "duration_seconds": ${unit_duration:-0}
  },
  "coverage": {
    "lines": ${line_coverage:-0},
    "functions": ${function_coverage:-0},
    "branches": ${branch_coverage:-0},
    "statements": ${statement_coverage:-0},
    "meets_threshold": $([ "${line_coverage_int:-0}" -ge "$MIN_COVERAGE" ] && echo "true" || echo "false")
  },
  "component_tests": {
    "component_count": $component_files,
    "test_count": $test_files,
    "coverage_ratio": ${test_ratio:-0}
  },
  "e2e_tests": {
    "available": $([ -f "../../package.json" ] && grep -q "test:e2e" ../../package.json && echo "true" || echo "false"),
    "passed": ${passed_e2e:-0},
    "failed": ${failed_e2e:-0},
    "duration_seconds": ${e2e_duration:-0}
  }
}
EOF

echo "📄 Test validation report saved to meta-agent/state/test-validation-report.json"
echo "✅ Test validation completed successfully"