<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerQuarantineManager;
use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerRecoveryReport;
use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerRecoveryAction;
use PpPhp\Core\Platform\Event\Worker\Monitoring\WorkerStaleRecord;

final class WorkerQuarantineVerifier
{
    public function verify(string $basePath): array
    {
        $recovery = new WorkerRecoveryReport([
            [
                'workerId' => 'worker_quarantine_failed',
                'action' => WorkerRecoveryAction::QUARANTINE_CANDIDATE,
                'reason' => 'failed worker marked for quarantine',
                'classification' => WorkerStaleRecord::FAILED,
                'successful' => true,
                'performedAt' => date('c'),
            ],
            [
                'workerId' => 'worker_quarantine_hung',
                'action' => WorkerRecoveryAction::RESTART,
                'reason' => 'hung worker restarted',
                'classification' => WorkerStaleRecord::HUNG,
                'successful' => true,
                'performedAt' => date('c'),
            ],
        ], [
            'actions' => 2,
            'quarantineCandidate' => 1,
        ], [], date('c'));

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

        $report = $manager->quarantineFromRecovery($recovery);
        $released = $manager->release('worker_quarantine_failed');
        $loaded = $manager->load();
        $stats = $loaded->statistics();

        $checks = [
            'quarantine' => count($report->records()) === 1,
            'release' => $released,
            'statistics' => ($stats['records'] ?? 0) === 1 && ($stats['released'] ?? 0) === 1,
            'persistence' => $manager->store()->exists(),
        ];

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

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