<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Dispatcher\DelayedDispatcher;

final class DispatcherConsoleStateHydrator
{
    public function __construct(private readonly DispatcherRuntimeManager $manager) {}

    public function statistics(): array
    {
        $live = $this->manager->dispatcher()->statistics()->toArray();

        if (($live['executed'] ?? 0) > 0 || !$this->manager->store()->exists()) {
            return $live;
        }

        $persisted = $this->manager->load()->statistics();

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

    public function snapshot(): array
    {
        $live = $this->manager->dispatcher()->snapshot()->toArray();

        if (($live['statistics']['executed'] ?? 0) > 0 || !$this->manager->store()->exists()) {
            return $live;
        }

        $persisted = $this->manager->load()->snapshot();

        return $persisted !== [] ? $persisted : $live;
    }

    public function failed(): int
    {
        $stats = $this->statistics();

        return (int) ($stats['failed'] ?? 0);
    }

    public function executed(): int
    {
        $stats = $this->statistics();

        return (int) ($stats['executed'] ?? 0);
    }

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

    private function normalizeStatistics(array $stats): array
    {
        return [
            'queued' => (int) ($stats['queued'] ?? 0),
            'executed' => (int) ($stats['executed'] ?? 0),
            'completed' => (int) ($stats['completed'] ?? 0),
            'retried' => (int) ($stats['retried'] ?? 0),
            'deadLettered' => (int) ($stats['deadLettered'] ?? 0),
            'failed' => (int) ($stats['failed'] ?? 0),
            'executionTimeMs' => (float) ($stats['executionTimeMs'] ?? 0),
            'averageExecutionTimeMs' => (float) ($stats['averageExecutionTimeMs'] ?? 0),
        ];
    }
}
