<?php
declare(strict_types=1);

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

final class WorkerPoolStatistics
{
    public function __construct(private readonly array $records = []) {}

    public function toArray(): array
    {
        $workers = count($this->records);
        $idle = 0;
        $busy = 0;
        $stopped = 0;
        $failed = 0;
        $capacity = 0;
        $activeJobs = 0;

        foreach ($this->records as $record) {
            if (!$record instanceof WorkerPoolRecord) {
                continue;
            }

            $state = $record->state();
            $idle += $state === WorkerPoolState::IDLE ? 1 : 0;
            $busy += $state === WorkerPoolState::BUSY ? 1 : 0;
            $stopped += $state === WorkerPoolState::STOPPED ? 1 : 0;
            $failed += $state === WorkerPoolState::FAILED ? 1 : 0;
            $capacity += $record->capacity();
            $activeJobs += $record->activeJobs();
        }

        return [
            'workers' => $workers,
            'idle' => $idle,
            'busy' => $busy,
            'stopped' => $stopped,
            'failed' => $failed,
            'capacity' => $capacity,
            'activeJobs' => $activeJobs,
            'utilization' => $capacity > 0 ? round(($activeJobs / $capacity) * 100, 2) : 0,
        ];
    }
}
