<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming\Broadcast;

final class StreamBroadcastStatistics
{
    public static function from(array $requests, array $results): array
    {
        $stats = ['broadcasts' => count($requests), 'targets' => 0, 'delivered' => 0, 'skipped' => 0, 'averageBroadcastTimeMs' => 0, 'throughput' => 0];
        $totalTime = 0.0;
        foreach ($results as $result) {
            $row = $result instanceof StreamBroadcastResult ? $result->toArray() : (array) $result;
            $stats['targets'] += (int) ($row['targets'] ?? 0);
            $stats['delivered'] += (int) ($row['delivered'] ?? 0);
            $stats['skipped'] += (int) ($row['skipped'] ?? 0);
            $totalTime += (float) ($row['broadcastTimeMs'] ?? 0);
        }
        $count = count($results);
        $stats['averageBroadcastTimeMs'] = $count > 0 ? round($totalTime / $count, 3) : 0;
        $stats['throughput'] = $totalTime > 0 ? round(($stats['delivered'] / max(0.001, $totalTime)) * 1000, 2) : 0;
        return $stats;
    }
}
