<?php

declare(strict_types=1);

namespace App\Framework\Discovery\Events;

use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Discovery\ValueObjects\DiscoveryContext;
use App\Framework\Discovery\ValueObjects\PerformanceMetrics;

/**
 * Event emitted when discovery performance analysis is completed
 *
 * Provides comprehensive performance metrics for telemetry and monitoring systems.
 */
final readonly class PerformanceAnalysisEvent
{
    public function __construct(
        public string $operationId,
        public DiscoveryContext $context,
        public PerformanceMetrics $metrics,
        public array $bottlenecks,
        public array $recommendations,
        public Timestamp $timestamp
    ) {
    }

    /**
     * Get telemetry data for monitoring systems
     */
    public function toTelemetryData(): array
    {
        return [
            'event_type' => 'discovery_performance_analysis',
            'operation_id' => $this->operationId,
            'timestamp' => $this->timestamp->toFloat(),
            'context' => [
                'paths' => $this->context->paths,
                'scan_type' => $this->context->scanType->value,
                'cache_enabled' => $this->context->options->useCache,
            ],
            'performance' => [
                'duration_ms' => $this->metrics->snapshot->duration?->toMilliseconds() ?? 0,
                'files_processed' => $this->metrics->snapshot->filesProcessed,
                'memory_peak_mb' => $this->metrics->snapshot->peakMemory->toMegabytes(),
                'memory_delta_mb' => $this->metrics->snapshot->memoryDelta?->toMegabytes() ?? 0,
                'cache_hits' => $this->metrics->snapshot->cacheHits,
                'cache_misses' => $this->metrics->snapshot->cacheMisses,
                'io_operations' => $this->metrics->snapshot->ioOperations,
                'errors' => $this->metrics->snapshot->errorsEncountered,
            ],
            'metrics' => [
                'throughput' => $this->metrics->throughput,
                'operation_size_score' => $this->metrics->operationSize->toDecimal(),
                'memory_efficiency_score' => $this->metrics->memoryEfficiency->toDecimal(),
                'cache_efficiency_score' => $this->metrics->cacheEfficiency->toDecimal(),
                'performance_score' => $this->metrics->performanceScore->toDecimal(),
                'efficiency_rating' => $this->metrics->getEfficiencyRating(),
            ],
            'issues' => [
                'bottlenecks' => $this->bottlenecks,
                'recommendations' => $this->recommendations,
                'bottleneck_count' => count($this->bottlenecks),
            ],
        ];
    }

    /**
     * Check if this represents a performance issue
     */
    public function hasPerformanceIssues(): bool
    {
        return ! empty($this->bottlenecks) ||
               $this->metrics->performanceScore->toDecimal() < 0.7;
    }

    /**
     * Get severity level for alerting
     */
    public function getSeverityLevel(): string
    {
        $score = $this->metrics->performanceScore->toDecimal();
        $bottleneckCount = count($this->bottlenecks);

        if ($score < 0.3 || $bottleneckCount >= 3) {
            return 'critical';
        } elseif ($score < 0.5 || $bottleneckCount >= 2) {
            return 'warning';
        } elseif ($score < 0.7 || $bottleneckCount >= 1) {
            return 'info';
        }

        return 'success';
    }
}
