<?php
declare(strict_types=1);

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

final class WorkerConsoleStateHydrator
{
    public function __construct(private readonly WorkerRuntimeManager $manager) {}

    public function workers(): array
    {
        $live = $this->manager->runtime()->workers()->toArray();
        if ($live !== [] || !$this->manager->store()->exists()) {
            return $live;
        }
        return $this->manager->load()->workers();
    }

    public function statistics(): array
    {
        $live = $this->manager->runtime()->statistics()->toArray();
        if (($live['workers'] ?? 0) > 0 || ($live['handled'] ?? 0) > 0 || !$this->manager->store()->exists()) {
            return $this->normalizeStatistics($live);
        }

        $persisted = $this->manager->load()->statistics();
        return $persisted !== [] ? $this->normalizeStatistics($persisted) : $this->normalizeStatistics($live);
    }

    public function lifecycle(): array
    {
        $live = $this->manager->runtime()->lifecycle()->all();
        if ($live !== [] || !$this->manager->store()->exists()) {
            return $live;
        }
        return $this->manager->load()->lifecycle();
    }

    public function persisted(): bool
    {
        return $this->manager->store()->exists();
    }

    private function normalizeStatistics(array $stats): array
    {
        return [
            'workers' => (int) ($stats['workers'] ?? 0),
            'running' => (int) ($stats['running'] ?? 0),
            'idle' => (int) ($stats['idle'] ?? 0),
            'stopped' => (int) ($stats['stopped'] ?? 0),
            'handled' => (int) ($stats['handled'] ?? 0),
            'failed' => (int) ($stats['failed'] ?? 0),
        ];
    }
}
