<?php

declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\Database\Migration\MigrationLoader;
use App\Framework\Database\Migration\MigrationVersionCollection;
use App\Framework\Database\Migration\Services\MigrationValidator;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;

try {
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();
    $collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);
    $bootstrapper = new AppBootstrapper(__DIR__ . '/../..', $collector, $memoryMonitor);
    $app = $bootstrapper->bootstrapConsole();
    $container = $app->getContainer();

    $loader = $container->get(MigrationLoader::class);
    $validator = $container->get(MigrationValidator::class);

    $migrations = $loader->loadMigrations();
    $appliedVersions = MigrationVersionCollection::fromStrings([]);

    echo "=== Loaded Migrations ===" . PHP_EOL;
    foreach ($migrations->toArray() as $migration) {
        echo "  - " . $migration->getVersion()->toString() . ": " . $migration->getDescription() . PHP_EOL;
    }
    echo PHP_EOL;

    echo "=== Running Pre-flight Checks ===" . PHP_EOL;
    $results = $validator->runPreFlightChecks($migrations, $appliedVersions);

    foreach ($results as $checkName => $result) {
        $status = $result['status'] ?? 'unknown';
        $severity = $result['severity'] ?? 'info';
        $message = $result['message'] ?? 'No message';

        $icon = match($status) {
            'pass' => '✓',
            'fail' => '✗',
            'warning' => '⚠',
            default => '?'
        };

        echo "{$icon} {$checkName} [{$severity}]: {$message}" . PHP_EOL;

        if (isset($result['details']) && is_array($result['details'])) {
            foreach ($result['details'] as $key => $value) {
                if (is_array($value)) {
                    echo "    {$key}: " . json_encode($value) . PHP_EOL;
                } else {
                    echo "    {$key}: {$value}" . PHP_EOL;
                }
            }
        }
        echo PHP_EOL;
    }

    $criticalIssues = [];
    foreach ($results as $check => $result) {
        if ($result['status'] === 'fail' && ($result['severity'] ?? 'info') === 'critical') {
            $criticalIssues[] = $check . ': ' . $result['message'];
        }
    }

    if (! empty($criticalIssues)) {
        echo PHP_EOL . "CRITICAL ISSUES FOUND:" . PHP_EOL;
        foreach ($criticalIssues as $issue) {
            echo "  ✗ {$issue}" . PHP_EOL;
        }
    } else {
        echo "✓ All pre-flight checks passed!" . PHP_EOL;
    }

} catch (Throwable $e) {
    echo "Error: " . $e->getMessage() . PHP_EOL;
    echo "Trace: " . $e->getTraceAsString() . PHP_EOL;
}
