<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Distributed\DistributedRuntimeCoordinator;
use PpPhp\Core\Platform\Event\Distributed\DistributedWorkerRecord;

final class DistributedRuntimeVerifier
{
    public function verify(string $basePath): array
    {
        $coordinator = DistributedRuntimeCoordinator::resetInstance($basePath);
        $coordinator->clear();

        $one = $coordinator->registerWorker('distributed_worker_1', 'node_a', 2);
        $two = $coordinator->registerWorker('distributed_worker_2', 'node_b', 1);

        $coordinator->heartbeat('node_a', 'distributed_worker_1', DistributedWorkerRecord::BUSY, 1);
        $coordinator->heartbeat('node_b', 'distributed_worker_2', DistributedWorkerRecord::IDLE, 0);

        $snapshot = $coordinator->save();

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

        $stats = $second->snapshot()->statistics();

        $checks = [
            'registration' => $coordinator->registry()->count() === 2,
            'heartbeat' => ($stats['busy'] ?? 0) === 1 && ($stats['idle'] ?? 0) === 1,
            'nodes' => ($stats['nodes'] ?? 0) === 2,
            'capacity' => ($stats['capacity'] ?? 0) === 3,
            'persistence' => $second->store()->exists(),
            'hydration' => $second->registry()->count() === 2,
        ];

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

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