<?php
declare(strict_types=1);

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

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

final class DispatcherCrossProcessHydrationVerifier
{
    public function verify(string $basePath): array
    {
        $first = DispatcherRuntimeManager::resetInstance($basePath);
        $first->clear();

        $first->dispatcher()->queue()->enqueue('dispatcher.cross.process');
        $run = $first->dispatcher()->run(static function (): void {});
        $first->save();

        /*
         * Simulate a separate CLI invocation by resetting the in-memory singleton.
         * The new runtime has zero live statistics, so consoleState() must hydrate
         * from storage/cache/events/runtime/dispatcher-runtime.json.
         */
        $second = DispatcherRuntimeManager::resetInstance($basePath);
        $state = $second->consoleState();

        $stats = $state->statistics();
        $snapshot = $state->snapshot();

        $checks = [
            'run' => $run === 1,
            'persisted' => $state->persisted(),
            'hydratedStats' => ($stats['executed'] ?? 0) === 1 && ($stats['completed'] ?? 0) === 1,
            'hydratedExecuted' => $state->executed() === 1,
            'hydratedFailed' => $state->failed() === 0,
            'hydratedSnapshot' => isset($snapshot['queue'], $snapshot['scheduler'], $snapshot['retry'], $snapshot['statistics']),
        ];

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

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