<?php

declare(strict_types=1);

namespace App\Framework\Performance;

class PerformanceMeasurement
{
    public float $startTime;
    public int $startMemory;
    public ?float $endTime = null;
    public ?int $endMemory = null;

    public function __construct(
        public readonly string $label,
        public readonly PerformanceCategory $category,
    ) {
        $this->startTime = microtime(true);
        $this->startMemory = memory_get_usage();
    }

    public function end(): void
    {
        if ($this->endTime === null) {
            $this->endTime = microtime(true);
            $this->endMemory = memory_get_usage();
        }
    }

    public function isCompleted(): bool
    {
        return $this->endTime !== null;
    }

    public function getLabel(): string
    {
        return $this->label;
    }

    public function getCategory(): PerformanceCategory
    {
        return $this->category;
    }

    public function getDurationMs(): float
    {
        if ($this->endTime === null) {
            return 0.0;
        }

        return ($this->endTime - $this->startTime) * 1000;
    }

    public function getMemoryUsageMb(): float
    {
        if ($this->endMemory === null) {
            return 0.0;
        }

        return ($this->endMemory - $this->startMemory) / 1024 / 1024;
    }

    public function getStartTime(): float
    {
        return $this->startTime;
    }

    public function getEndTime(): ?float
    {
        return $this->endTime;
    }

    public function getStartMemory(): int
    {
        return $this->startMemory;
    }

    public function getEndMemory(): ?int
    {
        return $this->endMemory;
    }
}
