<?php
declare(strict_types=1);

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

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

final class DistributedNodeFailureDetector
{
    public function __construct(private readonly DistributedFailoverPolicy $policy = new DistributedFailoverPolicy()) {}

    public function inspect(DistributedRuntimeCoordinator $runtime): array
    {
        $byNode = [];

        foreach ($runtime->registry()->toArray() as $worker) {
            $nodeId = (string) ($worker['nodeId'] ?? '');
            if ($nodeId === '') {
                continue;
            }

            $byNode[$nodeId] ??= [];
            $byNode[$nodeId][] = $worker;
        }

        $records = [];
        foreach ($byNode as $nodeId => $workers) {
            $records[] = DistributedNodeHealthRecord::fromWorkers($nodeId, $workers, $this->policy)->toArray();
        }

        return $records;
    }
}
