<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Worker\DispatcherWorkerAdapter;
use PpPhp\Core\Platform\Event\Worker\Pool\WorkerPoolManager;

final class WorkerPoolVerifier
{
    public function verify(string $basePath): array
    {
        $manager = WorkerPoolManager::resetInstance($basePath);
        $manager->clear();

        $manager->pool()->register(new DispatcherWorkerAdapter('pool_verify_1', 'verify-worker-1'));
        $manager->pool()->register(new DispatcherWorkerAdapter('pool_verify_2', 'verify-worker-2'));

        $acquired = $manager->pool()->acquire();
        $released = $acquired ? $manager->pool()->release($acquired->id()) : false;
        $snapshot = $manager->save();

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

        $stats = $second->pool()->statistics()->toArray();

        $checks = [
            'registration' => $manager->pool()->registry()->count() === 2,
            'acquire' => $acquired !== null && $acquired->activeJobs() === 1,
            'release' => $released,
            'statistics' => ($stats['workers'] ?? 0) === 2 && ($stats['idle'] ?? 0) === 2,
            'persistence' => $second->store()->exists() && count($snapshot->workers()) === 2,
            'hydration' => $second->pool()->registry()->count() === 2,
        ];

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

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