<?php
declare(strict_types=1);

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

final class WorkerHealthMonitor
{
    public function __construct(private readonly int $staleAfterSeconds = 60) {}

    public function inspect(WorkerHeartbeatCollection $heartbeats): WorkerHealthSnapshot
    {
        $records = [];

        foreach ($heartbeats->all() as $heartbeat) {
            $records[] = WorkerHealthRecord::fromHeartbeat($heartbeat, $this->staleAfterSeconds)->toArray();
        }

        return new WorkerHealthSnapshot($records, $this->statistics($records), date('c'));
    }

    private function statistics(array $records): array
    {
        $stats = [
            'workers' => count($records),
            'healthy' => 0,
            'idle' => 0,
            'busy' => 0,
            'degraded' => 0,
            'stalled' => 0,
            'offline' => 0,
            'failed' => 0,
        ];

        foreach ($records as $record) {
            $state = (string) ($record['status']['state'] ?? WorkerHealthStatus::HEALTHY);

            if (($record['status']['healthy'] ?? false) === true) {
                $stats['healthy']++;
            }

            if (array_key_exists($state, $stats)) {
                $stats[$state]++;
            }
        }

        return $stats;
    }
}
