<?php
declare(strict_types=1);

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

final class PublisherStatistics
{
    public static function from(array $publishers, array $requests, array $results): array
    {
        $published = 0;
        $failed = 0;
        $bytes = 0;
        $totalTime = 0.0;

        foreach ($results as $result) {
            $row = $result instanceof PublishResult ? $result->toArray() : (array) $result;
            if (($row['published'] ?? false) === true) {
                $published++;
            } else {
                $failed++;
            }

            $bytes += (int) ($row['bytes'] ?? 0);
            $totalTime += (float) ($row['publishTimeMs'] ?? 0);
        }

        $messages = count($results);

        return [
            'publishers' => count($publishers),
            'requests' => count($requests),
            'messages' => $messages,
            'published' => $published,
            'failed' => $failed,
            'bytes' => $bytes,
            'averagePublishTimeMs' => $messages > 0 ? round($totalTime / $messages, 3) : 0,
            'throughput' => $totalTime > 0 ? round(($published / max(0.001, $totalTime)) * 1000, 2) : 0,
        ];
    }
}
