<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerRecoveryManager;
use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerRecoveryPolicy;
use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerStaleReport;

final class WorkerRecoveryVerifier
{
    public function verify(string $basePath): array
    {
        $stale = new WorkerStaleReport([
            ['workerId' => 'worker_recovery_stale', 'classification' => 'stale', 'stale' => true],
            ['workerId' => 'worker_recovery_hung', 'classification' => 'hung', 'stale' => true],
            ['workerId' => 'worker_recovery_offline', 'classification' => 'offline', 'stale' => true],
            ['workerId' => 'worker_recovery_failed', 'classification' => 'failed', 'stale' => true],
            ['workerId' => 'worker_recovery_healthy', 'classification' => 'healthy', 'stale' => false],
        ], [
            'workers' => 5,
            'healthy' => 1,
            'stale' => 1,
            'hung' => 1,
            'offline' => 1,
            'failed' => 1,
            'unhealthy' => 4,
        ], WorkerRecoveryPolicy::default()->toArray(), date('c'));

        $manager = WorkerRecoveryManager::resetInstance($basePath);
        $manager->clear();

        $report = $manager->recover($stale);
        $loaded = $manager->load();
        $stats = $loaded->statistics();

        $checks = [
            'actions' => ($stats['actions'] ?? 0) === 4,
            'restart' => ($stats['restart'] ?? 0) === 1,
            'rehydrate' => ($stats['rehydrate'] ?? 0) === 1,
            'reallocate' => ($stats['reallocate'] ?? 0) === 1,
            'quarantineCandidate' => ($stats['quarantineCandidate'] ?? 0) === 1,
            'successful' => ($stats['successful'] ?? 0) === 4,
            'persistence' => $manager->store()->exists(),
            'records' => count($report->actions()) === 4,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'actions' => $stats['actions'] ?? 0,
                'restart' => $stats['restart'] ?? 0,
                'rehydrate' => $stats['rehydrate'] ?? 0,
                'reallocate' => $stats['reallocate'] ?? 0,
                'quarantineCandidate' => $stats['quarantineCandidate'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
