<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\Core\AppBootstrapper;
use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\ValueObjects\SqlQuery;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;

echo "🔍 Queue Tables Analysis via Framework\n";
echo "=====================================\n\n";

try {
    // Bootstrap framework
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();
    $collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);

    $bootstrapper = new AppBootstrapper(__DIR__ . '/../..', $collector, $memoryMonitor);
    $container = $bootstrapper->bootstrapWorker();

    $connection = $container->get(ConnectionInterface::class);

    $queueTables = [
        'job_history', 'job_metrics', 'dead_letter_jobs', 'job_batches',
        'worker_health_checks', 'queue_workers', 'distributed_locks',
        'job_assignments', 'failover_events', 'job_index', 'job_progress',
        'job_dependencies', 'job_chains',
    ];

    foreach ($queueTables as $table) {
        try {
            echo "📊 Table: $table\n";
            echo str_repeat('-', 40) . "\n";

            // Try to query the table structure
            $result = $connection->query(SqlQuery::create("DESCRIBE $table"));
            $columns = $result->fetchAll();

            if (empty($columns)) {
                echo "❌ Table exists but has NO COLUMNS\n";
            } else {
                echo "✅ Columns: " . count($columns) . "\n";
                foreach ($columns as $col) {
                    echo "   • {$col['Field']} ({$col['Type']})\n";
                }
            }

            // Check row count
            $result = $connection->query(SqlQuery::create("SELECT COUNT(*) as count FROM $table"));
            $count = $result->fetchAll()[0] ?? ['count' => 0];
            echo "📈 Rows: {$count['count']}\n";

        } catch (Exception $e) {
            if (strpos($e->getMessage(), "doesn't exist") !== false ||
                strpos($e->getMessage(), "Table") !== false ||
                strpos($e->getMessage(), "42S02") !== false) {
                echo "❌ Table does NOT exist\n";
            } else {
                echo "❌ Error: " . $e->getMessage() . "\n";
            }
        }
        echo "\n";
    }

    // Also check what tables DO exist
    echo "📋 All existing tables:\n";
    echo "======================\n";

    try {
        $result = $connection->query(SqlQuery::create("SHOW TABLES"));
        $tables = $result->fetchAll();
        foreach ($tables as $table) {
            $tableName = array_values($table)[0];
            echo "  • $tableName\n";
        }
    } catch (Exception $e) {
        echo "❌ Could not list tables: " . $e->getMessage() . "\n";
    }

} catch (Exception $e) {
    echo "❌ Framework bootstrap failed: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}

echo "\n✅ Database analysis completed!\n";
