<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerHeartbeatManager;

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

        $first->record('worker_heartbeat_001', 'running', 5, 0, 'event.one');
        $first->record('worker_heartbeat_002', 'idle', 2, 0, 'event.two');
        $snapshot = $first->save();

        $second = WorkerHeartbeatManager::resetInstance($basePath);
        $second->hydrate();

        $collection = $second->collection();
        $loaded = $second->load();

        $stats = $loaded->statistics();

        $checks = [
            'record' => $snapshot->statistics()['workers'] === 2,
            'persistence' => $second->store()->exists(),
            'hydration' => $collection->count() === 2,
            'statistics' => ($stats['running'] ?? 0) === 1 && ($stats['idle'] ?? 0) === 1,
            'handled' => ($stats['handled'] ?? 0) === 7,
        ];

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

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