<?php
declare(strict_types=1);

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

final class StreamSubscriberStatistics
{
    public static function from(array $subscribers, array $results): array
    {
        $stats = [
            'subscribers' => count($subscribers),
            'active' => 0,
            'paused' => 0,
            'messages' => 0,
            'acknowledged' => 0,
            'failed' => 0,
            'averageProcessingTimeMs' => 0,
            'throughput' => 0,
        ];

        foreach ($subscribers as $subscriber) {
            $status = (string) ($subscriber['status'] ?? StreamSubscriberStatus::ACTIVE);
            if ($status === StreamSubscriberStatus::ACTIVE) {
                $stats['active']++;
            } elseif ($status === StreamSubscriberStatus::PAUSED) {
                $stats['paused']++;
            }
        }

        $totalTime = 0.0;
        foreach ($results as $result) {
            $row = $result instanceof StreamSubscriberResult ? $result->toArray() : (array) $result;
            $stats['messages'] += (int) ($row['consumed'] ?? 0);
            $stats['acknowledged'] += (int) ($row['acknowledged'] ?? 0);
            $stats['failed'] += (int) ($row['failed'] ?? 0);
            $totalTime += (float) ($row['processingTimeMs'] ?? 0);
        }

        $count = count($results);
        $stats['averageProcessingTimeMs'] = $count > 0 ? round($totalTime / $count, 3) : 0;
        $stats['throughput'] = $totalTime > 0 ? round(($stats['messages'] / max(0.001, $totalTime)) * 1000, 2) : 0;

        return $stats;
    }
}
