<?php

declare(strict_types=1);

namespace Tests\Performance;

/**
 * Performance benchmark result value object
 */
final readonly class PerformanceBenchmarkResult
{
    public function __construct(
        public string $name,
        public int $iterations,
        public float $totalTimeMs,
        public float $avgTimeMs,
        public float $minTimeMs,
        public float $maxTimeMs,
        public float $medianTimeMs,
        public float $p95TimeMs,
        public float $p99TimeMs,
        public int $avgMemoryBytes,
        public int $peakMemoryBytes,
        public float $operationsPerSecond
    ) {}

    /**
     * Format result as human-readable string
     */
    public function toString(): string
    {
        $avgMemoryMb = round($this->avgMemoryBytes / 1024 / 1024, 2);
        $peakMemoryMb = round($this->peakMemoryBytes / 1024 / 1024, 2);

        return sprintf(
            "%s (%d iterations):\n" .
            "  Time:   avg=%.2fms, min=%.2fms, max=%.2fms, median=%.2fms\n" .
            "  P95:    %.2fms, P99: %.2fms\n" .
            "  Memory: avg=%.2fMB, peak=%.2fMB\n" .
            "  Throughput: %.2f ops/sec",
            $this->name,
            $this->iterations,
            $this->avgTimeMs,
            $this->minTimeMs,
            $this->maxTimeMs,
            $this->medianTimeMs,
            $this->p95TimeMs,
            $this->p99TimeMs,
            $avgMemoryMb,
            $peakMemoryMb,
            $this->operationsPerSecond
        );
    }

    /**
     * Convert to array for JSON serialization
     */
    public function toArray(): array
    {
        return [
            'name' => $this->name,
            'iterations' => $this->iterations,
            'time' => [
                'total_ms' => round($this->totalTimeMs, 2),
                'avg_ms' => round($this->avgTimeMs, 4),
                'min_ms' => round($this->minTimeMs, 4),
                'max_ms' => round($this->maxTimeMs, 4),
                'median_ms' => round($this->medianTimeMs, 4),
                'p95_ms' => round($this->p95TimeMs, 4),
                'p99_ms' => round($this->p99TimeMs, 4),
            ],
            'memory' => [
                'avg_bytes' => $this->avgMemoryBytes,
                'avg_mb' => round($this->avgMemoryBytes / 1024 / 1024, 2),
                'peak_bytes' => $this->peakMemoryBytes,
                'peak_mb' => round($this->peakMemoryBytes / 1024 / 1024, 2),
            ],
            'throughput' => [
                'ops_per_second' => round($this->operationsPerSecond, 2),
            ],
        ];
    }
}
