#!/bin/bash

# Performance validation for Trip With Us

echo "=== Performance Validation ==="

# Configuration
BUILD_TIMEOUT=120
BUNDLE_SIZE_LIMIT=5242880  # 5MB in bytes
LIGHTHOUSE_TIMEOUT=300

# Create performance reports directory
mkdir -p ../state/performance-reports

# Build performance test
echo "⚡ Testing build performance..."
build_start=$(date +%s)

if timeout $BUILD_TIMEOUT cd ../.. && npm run build > meta-agent/state/performance-reports/build.log 2>&1; then
    build_end=$(date +%s)
    build_duration=$((build_end - build_start))
    
    echo "✅ Build completed in ${build_duration}s"
    
    # Analyze build output
    if [ -d "../../dist" ]; then
        # Calculate bundle sizes
        total_size=$(du -b ../../dist 2>/dev/null | cut -f1 || echo "0")
        js_size=$(find ../../dist -name "*.js" -exec du -b {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
        css_size=$(find ../../dist -name "*.css" -exec du -b {} + 2>/dev/null | awk '{sum+=$1} END {print sum+0}')
        
        echo "📊 Bundle Analysis:"
        echo "  Total size: $(($total_size / 1024))KB"
        echo "  JavaScript: $(($js_size / 1024))KB"
        echo "  CSS: $(($css_size / 1024))KB"
        
        # Check against limits
        if [ "$total_size" -le "$BUNDLE_SIZE_LIMIT" ]; then
            echo "✅ Bundle size within limits"
        else
            echo "⚠️  Bundle size exceeds limit ($(($total_size / 1024))KB > $(($BUNDLE_SIZE_LIMIT / 1024))KB)"
        fi
        
        # Find largest files
        echo "📦 Largest files:"
        find ../../dist -type f -exec du -b {} + 2>/dev/null | sort -nr | head -5 | while read size file; do
            echo "  $(($size / 1024))KB - $(basename $file)"
        done
    else
        echo "❌ Build directory not found"
        exit 1
    fi
else
    echo "❌ Build failed or timed out"
    cat ../state/performance-reports/build.log | tail -20
    exit 1
fi

# Development server startup performance
echo "⚡ Testing dev server startup..."
if [ -f "../../package.json" ] && grep -q "dev" ../../package.json; then
    dev_start=$(date +%s)
    
    # Start dev server in background and test when it's ready
    cd ../.. && npm run dev > meta-agent/state/performance-reports/dev-server.log 2>&1 &
    dev_pid=$!
    
    # Wait for server to be ready (check port)
    max_wait=60
    wait_time=0
    
    while [ $wait_time -lt $max_wait ]; do
        if curl -s "http://localhost:8080" >/dev/null 2>&1; then
            dev_end=$(date +%s)
            dev_startup_time=$((dev_end - dev_start))
            echo "✅ Dev server ready in ${dev_startup_time}s"
            break
        fi
        sleep 2
        wait_time=$((wait_time + 2))
    done
    
    # Kill dev server
    kill $dev_pid 2>/dev/null
    wait $dev_pid 2>/dev/null
    
    if [ $wait_time -ge $max_wait ]; then
        echo "❌ Dev server startup timed out"
    fi
else
    echo "⚠️  Dev server script not found"
fi

# Code analysis for performance issues
echo "🔍 Analyzing code for performance issues..."

# Check for large imports
large_imports=$(grep -r "import.*from.*['\"]\." ../../src/ --include="*.ts" --include="*.tsx" 2>/dev/null | wc -l)
default_imports=$(grep -r "import.*\*.*as" ../../src/ --include="*.ts" --include="*.tsx" 2>/dev/null | wc -l)

echo "📊 Import Analysis:"
echo "  Relative imports: $large_imports"
echo "  Namespace imports: $default_imports"

if [ "$default_imports" -gt 10 ]; then
    echo "⚠️  Consider using named imports for better tree shaking"
fi

# Check for performance anti-patterns
console_logs=$(grep -r "console\." ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
debugger_statements=$(grep -r "debugger" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)

echo "📊 Code Quality:"
echo "  Console statements: $console_logs"
echo "  Debugger statements: $debugger_statements"

if [ "$console_logs" -gt 20 ]; then
    echo "⚠️  High number of console statements - consider removing for production"
fi

if [ "$debugger_statements" -gt 0 ]; then
    echo "❌ Debugger statements found - remove before production"
    grep -rn "debugger" ../../src/ --include="*.ts" --include="*.tsx" | head -5
fi

# React-specific performance checks
echo "🔍 Checking React performance patterns..."

# Check for inline functions in JSX
inline_functions=$(grep -r "onClick={.*=>" ../../src/ --include="*.tsx" | wc -l)
inline_objects=$(grep -r "style={{" ../../src/ --include="*.tsx" | wc -l)

echo "📊 React Performance:"
echo "  Inline functions: $inline_functions"
echo "  Inline style objects: $inline_objects"

if [ "$inline_functions" -gt 50 ]; then
    echo "⚠️  High number of inline functions - consider useCallback"
fi

if [ "$inline_objects" -gt 20 ]; then
    echo "⚠️  High number of inline style objects - consider CSS classes"
fi

# Check for useMemo and useCallback usage
usememo_usage=$(grep -r "useMemo\|useCallback" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
echo "  useMemo/useCallback usage: $usememo_usage"

# Check for React.memo usage
react_memo=$(grep -r "React\.memo\|memo(" ../../src/ --include="*.tsx" | wc -l)
echo "  React.memo usage: $react_memo"

# Bundle analyzer (if available)
if command -v webpack-bundle-analyzer >/dev/null 2>&1; then
    echo "📊 Running bundle analysis..."
    if [ -f "../../dist/stats.json" ]; then
        webpack-bundle-analyzer ../../dist/stats.json --report --mode static --output ../state/performance-reports/bundle-report.html
        echo "✅ Bundle report generated: meta-agent/state/performance-reports/bundle-report.html"
    else
        echo "⚠️  Bundle stats not available"
    fi
fi

# Lighthouse performance test (if Chrome is available)
if command -v google-chrome >/dev/null 2>&1 || command -v chromium-browser >/dev/null 2>&1; then
    echo "🏠 Running Lighthouse performance audit..."
    
    # Start dev server for testing
    cd ../.. && npm run dev > /dev/null 2>&1 &
    lighthouse_dev_pid=$!
    
    # Wait for server
    sleep 10
    
    if curl -s "http://localhost:8080" >/dev/null 2>&1; then
        # Run Lighthouse
        lighthouse_output=$(npx lighthouse http://localhost:8080 --output json --chrome-flags="--headless --no-sandbox" --quiet 2>/dev/null || echo "")
        
        if [ -n "$lighthouse_output" ]; then
            # Parse Lighthouse results
            performance_score=$(echo "$lighthouse_output" | jq '.categories.performance.score * 100' 2>/dev/null || echo "0")
            accessibility_score=$(echo "$lighthouse_output" | jq '.categories.accessibility.score * 100' 2>/dev/null || echo "0")
            best_practices_score=$(echo "$lighthouse_output" | jq '.categories["best-practices"].score * 100' 2>/dev/null || echo "0")
            
            echo "📊 Lighthouse Scores:"
            echo "  Performance: ${performance_score}%"
            echo "  Accessibility: ${accessibility_score}%"
            echo "  Best Practices: ${best_practices_score}%"
            
            # Save full report
            echo "$lighthouse_output" > ../state/performance-reports/lighthouse.json
            
            # Check thresholds
            performance_int=${performance_score%.*}
            if [ "$performance_int" -ge 70 ]; then
                echo "✅ Performance score acceptable"
            else
                echo "⚠️  Performance score below threshold (<70%)"
            fi
        else
            echo "⚠️  Lighthouse audit failed"
        fi
    else
        echo "❌ Could not start dev server for Lighthouse"
    fi
    
    # Cleanup
    kill $lighthouse_dev_pid 2>/dev/null
    wait $lighthouse_dev_pid 2>/dev/null
else
    echo "⚠️  Chrome not available for Lighthouse audit"
fi

# Generate performance report
cat > ../state/performance-validation-report.json << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "build": {
    "duration_seconds": ${build_duration:-0},
    "total_size_bytes": ${total_size:-0},
    "js_size_bytes": ${js_size:-0},
    "css_size_bytes": ${css_size:-0},
    "within_size_limit": $([ "${total_size:-0}" -le "$BUNDLE_SIZE_LIMIT" ] && echo "true" || echo "false")
  },
  "dev_server": {
    "startup_time_seconds": ${dev_startup_time:-0}
  },
  "code_analysis": {
    "console_statements": $console_logs,
    "debugger_statements": $debugger_statements,
    "inline_functions": $inline_functions,
    "inline_objects": $inline_objects,
    "usememo_usage": $usememo_usage,
    "react_memo_usage": $react_memo
  },
  "lighthouse": {
    "performance_score": ${performance_score:-0},
    "accessibility_score": ${accessibility_score:-0},
    "best_practices_score": ${best_practices_score:-0}
  }
}
EOF

echo "📄 Performance report saved to meta-agent/state/performance-validation-report.json"
echo "✅ Performance validation completed"