<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Dispatcher\Validation;

use PpPhp\Core\Platform\Event\Dispatcher\Runtime\DispatcherRuntimeManager;

final class DispatcherRuntimeSynchronizationVerifier
{
    public function verify(string $basePath): array
    {
        $manager = DispatcherRuntimeManager::resetInstance($basePath);
        $dispatcher = $manager->dispatcher();

        $dispatcher->queue()->enqueue('dispatcher.persistence.queued');
        $run = $dispatcher->run(static function (): void {});
        $saved = $manager->save();
        $loaded = $manager->load();

        $sameInstance = $manager === DispatcherRuntimeManager::instance($basePath);
        $stats = $dispatcher->statistics()->toArray();

        $checks = [
            'singleton' => $sameInstance,
            'runtimeExecution' => $run === 1,
            'statistics' => ($stats['executed'] ?? 0) === 1 && ($stats['completed'] ?? 0) === 1,
            'persistence' => $manager->store()->exists(),
            'loadedState' => (($loaded->statistics()['executed'] ?? 0) === 1),
            'snapshot' => isset($saved->snapshot()['queue'], $saved->snapshot()['scheduler'], $saved->snapshot()['statistics']),
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Dispatcher runtime sync failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'executed' => $stats['executed'] ?? 0,
                'completed' => $stats['completed'] ?? 0,
                'persisted' => $manager->store()->exists(),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
