#!/bin/bash

# Statistics Module Validation Script
# This script validates that the Statistics module is properly installed and configured

set -e

echo "================================"
echo "Statistics Module Validation"
echo "================================"
echo ""

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

# Counters
PASSED=0
FAILED=0
WARNINGS=0

# Function to print colored output
check_pass() {
  echo -e "${GREEN}✓${NC} $1"
  ((PASSED++))
}

check_fail() {
  echo -e "${RED}✗${NC} $1"
  ((FAILED++))
}

check_warn() {
  echo -e "${YELLOW}⚠${NC} $1"
  ((WARNINGS++))
}

check_info() {
  echo -e "${BLUE}ℹ${NC} $1"
}

# Section 1: File Structure
echo "🔍 Checking file structure..."
echo ""

# Check directories
DIRS=(
  "app/Http/Controllers/Api/Statistics"
  "app/Services/Statistics"
  "app/Models/Modules/Statistics/Models"
  "database/migrations"
  "storage/app/reports"
  "storage/app/exports"
)

for dir in "${DIRS[@]}"; do
  if [ -d "$dir" ]; then
    check_pass "Directory exists: $dir"
  else
    check_warn "Directory not found: $dir (will be created on demand)"
  fi
done

# Check files
FILES=(
  "app/Http/Controllers/Api/Statistics/MatchController.php"
  "app/Http/Controllers/Api/Statistics/EventController.php"
  "app/Http/Controllers/Api/Statistics/MvpController.php"
  "app/Http/Controllers/Api/Statistics/AnalyticsController.php"
  "app/Http/Controllers/Api/Statistics/ReportController.php"
  "app/Http/Controllers/Api/Statistics/AiInsightController.php"
  "app/Services/Statistics/MatchStatisticsService.php"
  "app/Services/Statistics/EventTrackingService.php"
  "app/Services/Statistics/MvpCalculationService.php"
  "app/Services/Statistics/AnalyticsService.php"
  "app/Services/Statistics/ReportGenerationService.php"
  "app/Services/Statistics/AiInsightService.php"
  "app/Models/Modules/Statistics/Models/Match.php"
)

echo ""
echo "Checking controller files..."
for file in "${FILES[@]}"; do
  if [ -f "$file" ]; then
    check_pass "File exists: $file"
  else
    check_fail "File missing: $file"
  fi
done

# Section 2: Database
echo ""
echo "🗄️  Checking database..."
echo ""

php artisan tinker << EOF
<?php
use Illuminate\Support\Facades\Schema;

\$tables = [
    'matches',
    'match_teams',
    'match_events',
    'match_statistics',
    'player_match_statistics',
    'player_performance_indexes',
    'match_mvps',
    'mvp_votings',
    'match_report_exports',
    'match_performance_metrics',
    'match_live_feeds',
    'ai_match_insights'
];

foreach (\$tables as \$table) {
    if (Schema::hasTable(\$table)) {
        echo "✓ Table: \$table\n";
    } else {
        echo "✗ Missing table: \$table\n";
    }
}
EOF

# Section 3: Service Container
echo ""
echo "📦 Checking service container..."
echo ""

php artisan tinker << EOF
<?php
try {
    app('App\Services\Statistics\MatchStatisticsService');
    echo "✓ MatchStatisticsService registered\n";
} catch (\Exception \$e) {
    echo "✗ MatchStatisticsService not accessible\n";
}

try {
    app('App\Services\Statistics\EventTrackingService');
    echo "✓ EventTrackingService registered\n";
} catch (\Exception \$e) {
    echo "✗ EventTrackingService not accessible\n";
}

try {
    app('App\Services\Statistics\MvpCalculationService');
    echo "✓ MvpCalculationService registered\n";
} catch (\Exception \$e) {
    echo "✗ MvpCalculationService not accessible\n";
}

try {
    app('App\Services\Statistics\AnalyticsService');
    echo "✓ AnalyticsService registered\n";
} catch (\Exception \$e) {
    echo "✗ AnalyticsService not accessible\n";
}
EOF

# Section 4: Routes
echo ""
echo "🛣️  Checking API routes..."
echo ""

php artisan route:list | grep -E "matches.*POST|matches.*GET|matches.*PUT" | head -20 || check_warn "Routes may not be registered yet"

# Section 5: Migrations
echo ""
echo "⚙️  Checking migrations..."
echo ""

php artisan migrate:status | grep statistics || check_warn "No migration status found for statistics"

# Section 6: Performance Metrics
echo ""
echo "📊 Checking sport metrics..."
echo ""

php artisan tinker << EOF
<?php
use App\Models\Core\Master\Sport;
use App\Models\Modules\Statistics\Models\MatchPerformanceMetric;

\$sports = Sport::count();
\$metrics = MatchPerformanceMetric::count();

echo "Total Sports: \$sports\n";
echo "Performance Metrics: \$metrics\n";

if (\$metrics === 0) {
    echo "⚠  No performance metrics configured. Run seeder to create defaults.\n";
}
EOF

# Section 7: File Permissions
echo ""
echo "🔐 Checking file permissions..."
echo ""

if [ -w "storage/app" ]; then
  check_pass "Storage directory is writable"
else
  check_fail "Storage directory is not writable"
fi

if [ -w "storage/logs" ]; then
  check_pass "Logs directory is writable"
else
  check_fail "Logs directory is not writable"
fi

# Section 8: Configuration
echo ""
echo "⚙️  Checking configuration..."
echo ""

if grep -q "statistics" config/app.php; then
  check_pass "Statistics config found in app.php"
else
  check_warn "Statistics config not found in app.php"
fi

# Summary
echo ""
echo "================================"
echo "Validation Summary"
echo "================================"
echo -e "${GREEN}Passed:${NC}   $PASSED"
echo -e "${RED}Failed:${NC}   $FAILED"
echo -e "${YELLOW}Warnings:${NC} $WARNINGS"
echo "================================"
echo ""

if [ $FAILED -gt 0 ]; then
  echo -e "${RED}⚠️  Some checks failed. Please review the errors above.${NC}"
  exit 1
elif [ $WARNINGS -gt 0 ]; then
  echo -e "${YELLOW}⚠️  Installation complete with warnings. Review above for details.${NC}"
  exit 0
else
  echo -e "${GREEN}✓ All checks passed! Statistics module is ready.${NC}"
  exit 0
fi
