<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed\Queue\Validation;

use PpPhp\Core\Platform\Event\Distributed\DistributedRuntimeCoordinator;
use PpPhp\Core\Platform\Event\Distributed\Queue\DistributedQueueCoordinator;
use PpPhp\Core\Platform\Event\Distributed\Lease\DistributedLeaseManager;

final class DistributedQueueVerifier
{
    public function verify(string $basePath): array
    {
        $runtime = DistributedRuntimeCoordinator::resetInstance($basePath);
        $runtime->clear();
        $runtime->registerWorker('queue_worker_1', 'queue_node_a', 2);
        $runtime->registerWorker('queue_worker_2', 'queue_node_b', 1);

        $leases = DistributedLeaseManager::resetInstance($basePath);
        $leases->clear();

        $coordinator = DistributedQueueCoordinator::resetInstance($basePath);
        $coordinator->clear();

        $queue = $coordinator->registerQueue('events.default', 10);
        $counter = $coordinator->updateCounters('events.default', 5, 0);
        $partition = $coordinator->assignPartition('events.default', 'queue_node_a', 'queue_worker_1', 1);
        $dispatch = $coordinator->dispatch('events.default', 'job_queue_verify_1', 60);
        $coordinator->save();

        $second = DistributedQueueCoordinator::resetInstance($basePath);
        $second->hydrate();
        $stats = $second->snapshot()->statistics();

        $checks = [
            'queueRegistry' => $queue->queueName() === 'events.default',
            'counters' => $counter && ($stats['pending'] ?? 0) === 5,
            'partition' => $partition->queueName() === 'events.default' && ($stats['partitions'] ?? 0) === 1,
            'dispatch' => ($dispatch['dispatched'] ?? false) === true,
            'lease' => DistributedLeaseManager::instance($basePath)->collection()->count() >= 1,
            'persistence' => $second->store()->exists(),
            'hydration' => ($stats['queues'] ?? 0) === 1,
        ];

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

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