<?php
declare(strict_types=1);

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

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

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

        $heartbeat->record('worker_health_001', 'running', 5, 0, 'event.busy');
        $heartbeat->record('worker_health_002', 'idle', 2, 0, 'event.idle');
        $heartbeat->record('worker_health_003', 'failed', 1, 1, 'event.failed');
        $heartbeat->save();

        $health = WorkerHealthManager::resetInstance($basePath);
        $health->clear();

        $snapshot = $health->inspect($heartbeat->collection());
        $loaded = $health->load();
        $stats = $loaded->statistics();

        $checks = [
            'inspection' => count($snapshot->records()) === 3,
            'statistics' => ($stats['workers'] ?? 0) === 3 && ($stats['healthy'] ?? 0) === 2 && ($stats['failed'] ?? 0) === 1,
            'persistence' => $health->store()->exists(),
            'records' => count($loaded->records()) === 3,
        ];

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

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