<?php

namespace WPSN\Core;

defined('ABSPATH') || exit;

/**
 * Lightweight performance probe for diagnostics.
 *
 * This is intentionally simple (no external deps, no persistent storage).
 * Values are request-scoped and only intended for quick troubleshooting.
 */
final class PerfProbe
{
    private static bool $enabled = false;

    /** @var array<string,float> */
    private static array $starts = [];

    /** @var array<string,float> */
    private static array $durationsMs = [];

    private static float $requestStart = 0.0;

    private static int $queriesStart = 0;

    public static function init(bool $enabled): void
    {
        self::$enabled = $enabled;
        self::$requestStart = microtime(true);

        global $wpdb;
        self::$queriesStart = isset($wpdb) && isset($wpdb->num_queries) ? (int) $wpdb->num_queries : 0;
    }

    public static function enabled(): bool
    {
        return self::$enabled;
    }

    public static function start(string $name): void
    {
        if (!self::$enabled) {
            return;
        }
        $name = sanitize_key($name);
        if ($name === '') {
            return;
        }
        self::$starts[$name] = microtime(true);
    }

    public static function stop(string $name): void
    {
        if (!self::$enabled) {
            return;
        }
        $name = sanitize_key($name);
        if ($name === '') {
            return;
        }
        if (!isset(self::$starts[$name])) {
            return;
        }
        $ms = (microtime(true) - (float) self::$starts[$name]) * 1000.0;
        unset(self::$starts[$name]);

        if (!isset(self::$durationsMs[$name])) {
            self::$durationsMs[$name] = 0.0;
        }
        self::$durationsMs[$name] += $ms;
    }

    /**
     * Record an ad-hoc duration (ms) for a named metric.
     */
    public static function addMs(string $name, float $ms): void
    {
        if (!self::$enabled) {
            return;
        }
        $name = sanitize_key($name);
        if ($name === '') {
            return;
        }
        if (!isset(self::$durationsMs[$name])) {
            self::$durationsMs[$name] = 0.0;
        }
        self::$durationsMs[$name] += max(0.0, $ms);
    }

    /**
     * @return array<string,mixed>
     */
    public static function snapshot(): array
    {
        global $wpdb;

        $queriesNow = isset($wpdb) && isset($wpdb->num_queries) ? (int) $wpdb->num_queries : 0;

        $totalMs = self::$requestStart > 0 ? (microtime(true) - self::$requestStart) * 1000.0 : 0.0;

        $mem = function_exists('memory_get_peak_usage') ? (int) memory_get_peak_usage(true) : 0;

        return [
            'enabled' => self::$enabled,
            'total_ms' => (int) round($totalMs),
            'queries' => max(0, $queriesNow - self::$queriesStart),
            'memory_peak_bytes' => $mem,
            'metrics_ms' => self::$durationsMs,
        ];
    }
}
