<?php

namespace Openguru\OpenCartFramework\Support;

class ExecutionTimeProfiler
{
    private $startTime;
    private $checkpoints = [];

    public function start(): void
    {
        $this->startTime = microtime(true);
        $this->checkpoints = [['label' => 'start', 'time' => $this->startTime]];
    }

    public function addCheckpoint(string $label): void
    {
        $currentTime = microtime(true);
        $this->checkpoints[] = [
            'label' => $label,
            'time' => $currentTime
        ];
    }

    public function stop(): array
    {
        $endTime = microtime(true);
        $this->checkpoints[] = ['label' => 'End', 'time' => $endTime];

        $result = [
            'total_execution_time_ms' => round(($endTime - $this->startTime) * 1000, 2),
            'checkpoints' => []
        ];

        $total = count($this->checkpoints);

        for ($i = 1; $i < $total; $i++) {
            $prev = $this->checkpoints[$i - 1];
            $current = $this->checkpoints[$i];

            $result['checkpoints'][] = [
                'label' => $current['label'],
                'elapsed_since_previous_ms' => round(($current['time'] - $prev['time']) * 1000, 2)
            ];
        }

        return $result;
    }
}
