<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Queue\DeferredEvent;
use PpPhp\Core\Platform\Event\Worker\DispatcherWorkerAdapter;
use PpPhp\Core\Platform\Event\Worker\Runtime\WorkerRuntimeManager;

final class WorkerRuntimeSynchronizationVerifier
{
    public function verify(string $basePath): array
    {
        $first = WorkerRuntimeManager::resetInstance($basePath);
        $first->clear();
        $first->runtime()->register(new DispatcherWorkerAdapter('worker_persisted'));
        $first->runtime()->startAll();
        $first->runtime()->handle(DeferredEvent::fromEvent('worker.persistence'), static function (): void {});
        $first->save();

        $second = WorkerRuntimeManager::resetInstance($basePath);
        $state = $second->consoleState();

        $stats = $state->statistics();
        $workers = $state->workers();
        $lifecycle = $state->lifecycle();

        $checks = [
            'persistence' => $state->persisted(),
            'hydratedWorkers' => count($workers) === 1,
            'hydratedStats' => ($stats['workers'] ?? 0) === 1 && ($stats['handled'] ?? 0) === 1,
            'hydratedLifecycle' => count($lifecycle) >= 3,
            'singleton' => $second === WorkerRuntimeManager::instance($basePath),
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'workers' => $stats['workers'] ?? 0,
                'handled' => $stats['handled'] ?? 0,
                'lifecycleEvents' => count($lifecycle),
                'persisted' => $state->persisted(),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
