<?php

namespace App\Core;

/**
 * Performance Monitor - مراقبة الأداء
 * يسجل slow queries, memory usage, execution time
 */
class PerformanceMonitor
{
    private Logger $logger;
    private array $queries = [];
    private float $startTime;
    private int $startMemory;
    private array $config;
    private bool $enabled;

    public function __construct(Logger $logger, array $config = [])
    {
        $this->logger = $logger;
        $this->config = $config;
        $this->enabled = $config['enabled'] ?? true;
        $this->startTime = microtime(true);
        $this->startMemory = memory_get_usage();
    }

    /**
     * بدء مراقبة query
     */
    public function startQuery(string $sql, array $params = []): string
    {
        if (!$this->enabled) {
            return '';
        }

        $id = uniqid('query_', true);
        $this->queries[$id] = [
            'sql' => $sql,
            'params' => $params,
            'start_time' => microtime(true),
            'start_memory' => memory_get_usage()
        ];

        return $id;
    }

    /**
     * إنهاء مراقبة query
     */
    public function endQuery(string $id, int $rowCount = 0): void
    {
        if (!$this->enabled || !isset($this->queries[$id])) {
            return;
        }

        $query = $this->queries[$id];
        $executionTime = (microtime(true) - $query['start_time']) * 1000; // milliseconds
        $memoryUsed = memory_get_usage() - $query['start_memory'];

        $query['execution_time'] = $executionTime;
        $query['memory_used'] = $memoryUsed;
        $query['row_count'] = $rowCount;

        // تسجيل slow query
        $slowQueryThreshold = $this->config['slow_query_threshold'] ?? 1000; // 1 second
        if ($executionTime > $slowQueryThreshold) {
            $this->logger->warning('Slow query detected', [
                'sql' => $query['sql'],
                'execution_time_ms' => round($executionTime, 2),
                'memory_used' => $memoryUsed,
                'row_count' => $rowCount
            ]);
        }

        // تسجيل query performance
        if ($this->config['log_all_queries'] ?? false) {
            $this->logger->debug('Query executed', [
                'sql' => $query['sql'],
                'execution_time_ms' => round($executionTime, 2),
                'memory_used' => $memoryUsed
            ]);
        }

        unset($this->queries[$id]);
    }

    /**
     * تسجيل request performance
     */
    public function logRequest(string $method, string $uri, int $statusCode, float $executionTime): void
    {
        if (!$this->enabled) {
            return;
        }

        $memoryPeak = memory_get_peak_usage(true);
        $memoryUsage = memory_get_usage(true);

        $data = [
            'method' => $method,
            'uri' => $uri,
            'status_code' => $statusCode,
            'execution_time_ms' => round($executionTime * 1000, 2),
            'memory_peak_mb' => round($memoryPeak / 1024 / 1024, 2),
            'memory_usage_mb' => round($memoryUsage / 1024 / 1024, 2),
            'query_count' => count($this->queries)
        ];

        // تسجيل slow requests
        $slowRequestThreshold = $this->config['slow_request_threshold'] ?? 2000; // 2 seconds
        if ($executionTime * 1000 > $slowRequestThreshold) {
            $this->logger->warning('Slow request detected', $data);
        } else {
            $this->logger->info('Request completed', $data);
        }
    }

    /**
     * جلب إحصائيات الأداء
     */
    public function getStats(): array
    {
        $totalTime = (microtime(true) - $this->startTime) * 1000;
        $totalMemory = memory_get_usage() - $this->startMemory;
        $peakMemory = memory_get_peak_usage(true);

        return [
            'execution_time_ms' => round($totalTime, 2),
            'memory_used_mb' => round($totalMemory / 1024 / 1024, 2),
            'memory_peak_mb' => round($peakMemory / 1024 / 1024, 2),
            'query_count' => count($this->queries),
            'active_queries' => array_keys($this->queries)
        ];
    }

    /**
     * جلب slow queries
     */
    public function getSlowQueries(float $threshold = 1000): array
    {
        $slowQueries = [];
        foreach ($this->queries as $id => $query) {
            if (isset($query['execution_time']) && $query['execution_time'] > $threshold) {
                $slowQueries[] = $query;
            }
        }
        return $slowQueries;
    }

    /**
     * تفعيل/تعطيل المراقبة
     */
    public function setEnabled(bool $enabled): void
    {
        $this->enabled = $enabled;
    }
}
