<?php

declare(strict_types=1);

namespace App\Framework\Router;

final class RouterPerformanceMonitor
{
    /** @var array<string, array{count: int, total_time: float, avg_time: float}> */
    private array $routeStats = [];

    public function trackRouteMatch(string $route, float $duration): void
    {
        if (! isset($this->routeStats[$route])) {
            $this->routeStats[$route] = [
                'count' => 0,
                'total_time' => 0.0,
                'avg_time' => 0.0,
            ];
        }

        $this->routeStats[$route]['count']++;
        $this->routeStats[$route]['total_time'] += $duration;
        $this->routeStats[$route]['avg_time'] =
            $this->routeStats[$route]['total_time'] / $this->routeStats[$route]['count'];
    }

    /**
     * @param int $thresholdMs
     * @return array<string, array{count: int, total_time: float, avg_time: float}>
     */
    public function getSlowRoutes(int $thresholdMs = 10): array
    {
        return array_filter(
            $this->routeStats,
            fn (array $stats) => $stats['avg_time'] > $thresholdMs
        );
    }

    /**
     * @return array<string, array{count: int, total_time: float, avg_time: float}>
     */
    public function getAllStats(): array
    {
        return $this->routeStats;
    }

    public function reset(): void
    {
        $this->routeStats = [];
    }
}
