<?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\WorkerRuntime;

final class WorkerFoundationVerifier
{
    public function verify(): array
    {
        $runtime = new WorkerRuntime();
        $worker = new DispatcherWorkerAdapter('worker_verify', 'verify-worker');

        $runtime->register($worker);
        $runtime->startAll();

        $result = $runtime->handle(DeferredEvent::fromEvent('worker.verify'), static function (): void {});
        $runtime->stopAll();

        $summary = $runtime->summary();
        $stats = $runtime->statistics()->toArray();

        $checks = [
            'registration' => $runtime->workers()->count() === 1,
            'handle' => $result->ok(),
            'statistics' => ($stats['workers'] ?? 0) === 1 && ($stats['handled'] ?? 0) === 1,
            'lifecycle' => $runtime->lifecycle()->count() >= 4,
            'heartbeat' => isset($summary['workers'][0]['heartbeat']),
        ];

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

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