<?php

declare(strict_types=1);

namespace App\Framework\Mcp\Tools\Categories\Performance;

use App\Framework\Mcp\Core\Services\McpToolContext;
use App\Framework\Mcp\Core\ValueObjects\OutputFormat;
use App\Framework\Mcp\McpTool;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\Performance\PerformanceService;

final readonly class PerformanceTools
{
    public function __construct(
        private PerformanceService $performanceService,
        private McpToolContext $context
    ) {
    }

    #[McpTool(
        name: 'performance_summary',
        description: 'Get current performance summary and statistics with enhanced analysis',
        category: 'performance',
        tags: ['monitoring', 'stats', 'summary'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function getPerformanceSummary(OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                    'help' => 'Enable performance monitoring to get statistics',
                ];

                return $this->context->formatResult($result, $format);
            }

            $summary = $this->performanceService->getSummary();
            $requestStats = $this->performanceService->getRequestStats();

            $result = [
                'enabled' => true,
                'summary' => $summary,
                'request_stats' => $requestStats,
                'health_score' => $this->calculateHealthScore($requestStats),
                'total_operations' => count($this->performanceService->getMetrics()),
                'categories_monitored' => array_column(PerformanceCategory::cases(), 'value'),
                'timestamp' => date('Y-m-d H:i:s'),
                'generated_at' => microtime(true),
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    #[McpTool(
        name: 'performance_slowest',
        description: 'Get slowest operations with detailed timing information and optimization hints',
        category: 'performance',
        tags: ['monitoring', 'slow-queries', 'bottlenecks'],
        cacheable: true,
        defaultCacheTtl: 600
    )]
    public function getSlowestOperations(int $limit = 10, OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                    'help' => 'Enable performance monitoring to analyze slow operations',
                ];

                return $this->context->formatResult($result, $format);
            }

            $slowest = $this->performanceService->getSlowestOperations($limit);
            $totalMetrics = $this->performanceService->getMetrics();

            // Enhance with optimization hints
            $enhancedSlowest = array_map(function ($operation) {
                $operation['optimization_hints'] = $this->generateOptimizationHints($operation);
                $operation['severity'] = $this->calculateSeverity($operation);

                return $operation;
            }, $slowest);

            $result = [
                'enabled' => true,
                'slowest_operations' => $enhancedSlowest,
                'limit' => $limit,
                'total_operations_analyzed' => count($totalMetrics),
                'performance_threshold_exceeded' => count($enhancedSlowest),
                'avg_performance_impact' => $this->calculateAverageImpact($enhancedSlowest),
                'timestamp' => date('Y-m-d H:i:s'),
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    #[McpTool(
        name: 'performance_by_category',
        description: 'Get performance metrics grouped by category with trend analysis',
        category: 'performance',
        tags: ['monitoring', 'categories', 'analysis'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function getPerformanceByCategory(?string $category = null, OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                ];

                return $this->context->formatResult($result, $format);
            }

            $categoryFilter = null;
            if ($category) {
                $categoryFilter = PerformanceCategory::tryFrom($category);
                if (! $categoryFilter) {
                    $result = [
                        'error' => "Invalid category: {$category}",
                        'valid_categories' => array_column(PerformanceCategory::cases(), 'value'),
                    ];

                    return $this->context->formatResult($result, $format);
                }
            }

            $metrics = $this->performanceService->getMetrics($categoryFilter);

            // Group by category with enhanced analysis
            $byCategory = [];
            foreach ($metrics as $metric) {
                $cat = $metric->category->value;
                if (! isset($byCategory[$cat])) {
                    $byCategory[$cat] = [
                        'category' => $cat,
                        'operations' => [],
                        'total_duration_ms' => 0,
                        'operation_count' => 0,
                        'avg_duration_ms' => 0,
                        'max_duration_ms' => 0,
                        'min_duration_ms' => PHP_FLOAT_MAX,
                        'performance_issues' => 0,
                    ];
                }

                $duration = $metric->measurements['total_duration_ms'] ?? 0;
                $avgDuration = $metric->measurements['avg_duration_ms'] ?? 0;

                $byCategory[$cat]['operations'][] = [
                    'key' => $metric->key,
                    'duration_ms' => $duration,
                    'count' => $metric->measurements['count'] ?? 0,
                    'avg_duration_ms' => $avgDuration,
                    'severity' => $this->calculateSeverityFromDuration($avgDuration),
                ];

                $byCategory[$cat]['total_duration_ms'] += $duration;
                $byCategory[$cat]['operation_count']++;
                $byCategory[$cat]['max_duration_ms'] = max($byCategory[$cat]['max_duration_ms'], $avgDuration);
                $byCategory[$cat]['min_duration_ms'] = min($byCategory[$cat]['min_duration_ms'], $avgDuration);

                if ($avgDuration > 100) {
                    $byCategory[$cat]['performance_issues']++;
                }
            }

            // Calculate averages and add insights
            foreach ($byCategory as &$categoryData) {
                if ($categoryData['operation_count'] > 0) {
                    $categoryData['avg_duration_ms'] = $categoryData['total_duration_ms'] / $categoryData['operation_count'];
                }
                $categoryData['health_status'] = $this->getCategoryHealthStatus($categoryData);
                $categoryData['recommendations'] = $this->getCategoryRecommendations($categoryData);

                if ($categoryData['min_duration_ms'] === PHP_FLOAT_MAX) {
                    $categoryData['min_duration_ms'] = 0;
                }
            }

            $result = [
                'enabled' => true,
                'requested_category' => $category,
                'categories' => $byCategory,
                'available_categories' => array_column(PerformanceCategory::cases(), 'value'),
                'total_categories_analyzed' => count($byCategory),
                'overall_performance_score' => $this->calculateOverallCategoryScore($byCategory),
                'timestamp' => date('Y-m-d H:i:s'),
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    #[McpTool(
        name: 'performance_bottlenecks',
        description: 'Analyze and identify performance bottlenecks with prioritized recommendations',
        category: 'performance',
        tags: ['bottlenecks', 'analysis', 'optimization'],
        cacheable: true,
        defaultCacheTtl: 900
    )]
    public function analyzeBottlenecks(float $threshold_ms = 100.0, OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                ];

                return $this->context->formatResult($result, $format);
            }

            $metrics = $this->performanceService->getMetrics();
            $bottlenecks = [];

            foreach ($metrics as $metric) {
                $duration = $metric->measurements['total_duration_ms'] ?? 0;
                $count = $metric->measurements['count'] ?? 0;
                $avgDuration = $metric->measurements['avg_duration_ms'] ?? 0;

                if ($duration > $threshold_ms || $avgDuration > 50) {
                    $severity = $this->calculateBottleneckSeverity($duration, $avgDuration);
                    $impact = $this->calculateBottleneckImpact($duration, $count, $avgDuration);

                    $bottleneck = [
                        'key' => $metric->key,
                        'category' => $metric->category->value,
                        'total_duration_ms' => $duration,
                        'avg_duration_ms' => $avgDuration,
                        'call_count' => $count,
                        'severity' => $severity,
                        'impact_score' => $impact,
                        'priority_score' => $this->calculatePriorityScore($severity, $impact),
                        'recommendations' => $this->generateRecommendations($metric),
                        'estimated_improvement' => $this->estimateImprovementPotential($metric),
                    ];

                    $bottlenecks[] = $bottleneck;
                }
            }

            // Sort by priority score (highest impact first)
            usort($bottlenecks, fn ($a, $b) => $b['priority_score'] <=> $a['priority_score']);

            $result = [
                'enabled' => true,
                'threshold_ms' => $threshold_ms,
                'bottlenecks_found' => count($bottlenecks),
                'bottlenecks' => $bottlenecks,
                'total_metrics_analyzed' => count($metrics),
                'critical_bottlenecks' => count(array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical')),
                'high_impact_bottlenecks' => count(array_filter($bottlenecks, fn ($b) => $b['impact_score'] > 70)),
                'optimization_potential' => $this->calculateOptimizationPotential($bottlenecks),
                'timestamp' => date('Y-m-d H:i:s'),
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    #[McpTool(
        name: 'performance_report',
        description: 'Generate comprehensive performance report with actionable insights',
        category: 'performance',
        tags: ['report', 'comprehensive', 'analysis'],
        cacheable: true,
        defaultCacheTtl: 1800
    )]
    public function generatePerformanceReport(OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                ];

                return $this->context->formatResult($result, $format);
            }

            $report = $this->performanceService->generateReport('array');
            $requestStats = $this->performanceService->getRequestStats();
            $slowest = $this->performanceService->getSlowestOperations(5);
            $bottlenecksData = $this->analyzeBottlenecks(50.0, OutputFormat::ARRAY);
            $bottlenecks = is_array($bottlenecksData) && isset($bottlenecksData['bottlenecks']) ? $bottlenecksData['bottlenecks'] : [];

            $overallHealth = $this->calculateOverallHealth($requestStats, $bottlenecks);

            $result = [
                'enabled' => true,
                'executive_summary' => [
                    'overall_health' => $overallHealth,
                    'key_metrics' => [
                        'avg_response_time_ms' => $requestStats['time_ms'] ?? 0,
                        'memory_usage_mb' => round(($requestStats['memory_bytes'] ?? 0) / 1024 / 1024, 2),
                        'total_operations' => count($this->performanceService->getMetrics()),
                        'critical_issues' => count(array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical')),
                    ],
                    'recommendations_summary' => $this->generateExecutiveRecommendations($overallHealth, $bottlenecks),
                ],
                'detailed_analysis' => [
                    'performance_report' => $report,
                    'request_statistics' => $requestStats,
                    'top_5_slowest_operations' => $slowest,
                    'bottleneck_analysis' => [
                        'total_bottlenecks' => count($bottlenecks),
                        'critical_bottlenecks' => array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical'),
                        'high_impact_bottlenecks' => array_filter($bottlenecks, fn ($b) => $b['impact_score'] > 70),
                    ],
                ],
                'actionable_insights' => [
                    'immediate_actions' => $this->getImmediateActions($bottlenecks),
                    'optimization_roadmap' => $this->getOptimizationRoadmap($bottlenecks),
                    'monitoring_recommendations' => $this->getMonitoringRecommendations($overallHealth),
                ],
                'timestamp' => date('Y-m-d H:i:s'),
                'generated_at' => microtime(true),
                'report_metadata' => [
                    'analysis_depth' => 'comprehensive',
                    'data_freshness' => 'real-time',
                    'confidence_score' => $this->calculateConfidenceScore($bottlenecks),
                ],
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    #[McpTool(
        name: 'performance_reset',
        description: 'Reset all performance metrics and start fresh monitoring session',
        category: 'performance',
        tags: ['reset', 'cleanup', 'monitoring'],
        cacheable: false
    )]
    public function resetPerformanceMetrics(bool $confirm = false, OutputFormat $format = OutputFormat::ARRAY): mixed
    {
        try {
            if (! $confirm) {
                $result = [
                    'status' => 'confirmation_required',
                    'message' => 'Performance metrics reset requires explicit confirmation',
                    'usage' => 'Set confirm=true to proceed with reset',
                    'warning' => 'This will clear all historical performance data',
                ];

                return $this->context->formatResult($result, $format);
            }

            if (! $this->performanceService->isEnabled()) {
                $result = [
                    'error' => 'Performance monitoring is disabled',
                    'enabled' => false,
                ];

                return $this->context->formatResult($result, $format);
            }

            $metricsCount = count($this->performanceService->getMetrics());
            $this->performanceService->reset();

            $result = [
                'status' => 'success',
                'message' => 'Performance metrics have been reset successfully',
                'previous_metrics_count' => $metricsCount,
                'reset_timestamp' => date('Y-m-d H:i:s'),
                'monitoring_status' => 'active',
                'next_steps' => [
                    'Performance monitoring is now collecting fresh data',
                    'Allow some time for meaningful metrics to accumulate',
                    'Use performance_summary to monitor new data collection',
                ],
            ];

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, $format);
        }
    }

    private function calculateHealthScore(array $requestStats): array
    {
        $score = 100;
        $factors = [];

        $requestTime = $requestStats['time_ms'] ?? 0;
        if ($requestTime > 1000) {
            $score -= 40;
            $factors[] = 'Very slow response time (>1s)';
        } elseif ($requestTime > 500) {
            $score -= 20;
            $factors[] = 'Slow response time (>500ms)';
        } elseif ($requestTime > 200) {
            $score -= 10;
            $factors[] = 'Moderate response time (>200ms)';
        }

        $memoryMB = ($requestStats['memory_bytes'] ?? 0) / 1024 / 1024;
        if ($memoryMB > 128) {
            $score -= 25;
            $factors[] = 'High memory usage (>128MB)';
        } elseif ($memoryMB > 64) {
            $score -= 15;
            $factors[] = 'Moderate memory usage (>64MB)';
        }

        return [
            'score' => max(0, $score),
            'status' => $this->getHealthStatus($score),
            'factors' => $factors,
        ];
    }

    private function getHealthStatus(int $score): string
    {
        return match (true) {
            $score >= 90 => 'excellent',
            $score >= 75 => 'good',
            $score >= 60 => 'fair',
            $score >= 40 => 'poor',
            default => 'critical'
        };
    }

    private function generateOptimizationHints(array $operation): array
    {
        $hints = [];
        $duration = $operation['duration_ms'] ?? $operation['total_duration_ms'] ?? 0;
        $key = $operation['key'] ?? '';

        if ($duration > 1000) {
            $hints[] = 'Critical performance issue - requires immediate attention';
        }

        if (str_contains($key, 'database') || str_contains($key, 'query')) {
            $hints[] = 'Consider query optimization and database indexing';
        }

        if (str_contains($key, 'controller')) {
            $hints[] = 'Move heavy processing to background jobs';
        }

        if (str_contains($key, 'view') || str_contains($key, 'template')) {
            $hints[] = 'Enable template caching and optimize DOM operations';
        }

        return $hints;
    }

    private function calculateSeverity(array $operation): string
    {
        $duration = $operation['avg_duration_ms'] ?? $operation['duration_ms'] ?? 0;

        return match (true) {
            $duration > 1000 => 'critical',
            $duration > 500 => 'high',
            $duration > 200 => 'medium',
            default => 'low'
        };
    }

    private function calculateSeverityFromDuration(float $avgDuration): string
    {
        return match (true) {
            $avgDuration > 500 => 'critical',
            $avgDuration > 200 => 'high',
            $avgDuration > 100 => 'medium',
            default => 'low'
        };
    }

    private function calculateAverageImpact(array $operations): float
    {
        if (empty($operations)) {
            return 0.0;
        }

        $totalImpact = array_sum(array_column($operations, 'duration_ms'));

        return $totalImpact / count($operations);
    }

    private function getCategoryHealthStatus(array $categoryData): string
    {
        $avgDuration = $categoryData['avg_duration_ms'];
        $issueRatio = $categoryData['performance_issues'] / max(1, $categoryData['operation_count']);

        return match (true) {
            $avgDuration > 500 || $issueRatio > 0.5 => 'critical',
            $avgDuration > 200 || $issueRatio > 0.3 => 'warning',
            $avgDuration > 100 || $issueRatio > 0.1 => 'fair',
            default => 'good'
        };
    }

    private function getCategoryRecommendations(array $categoryData): array
    {
        $recommendations = [];
        $category = $categoryData['category'];
        $avgDuration = $categoryData['avg_duration_ms'];

        if ($avgDuration > 200) {
            $recommendations[] = match ($category) {
                'database' => 'Optimize database queries and add indexes',
                'controller' => 'Move heavy processing to service layer',
                'view' => 'Enable template caching',
                'cache' => 'Check cache backend performance',
                default => 'Profile and optimize operations'
            };
        }

        return $recommendations;
    }

    private function calculateOverallCategoryScore(array $categories): int
    {
        if (empty($categories)) {
            return 100;
        }

        $totalScore = 0;
        $categoryCount = 0;

        foreach ($categories as $category) {
            $score = 100;
            $avgDuration = $category['avg_duration_ms'];

            if ($avgDuration > 500) {
                $score -= 40;
            } elseif ($avgDuration > 200) {
                $score -= 20;
            } elseif ($avgDuration > 100) {
                $score -= 10;
            }

            $issueRatio = $category['performance_issues'] / max(1, $category['operation_count']);
            $score -= $issueRatio * 30;

            $totalScore += max(0, $score);
            $categoryCount++;
        }

        return (int) round($totalScore / $categoryCount);
    }

    private function calculateBottleneckSeverity(float $totalDuration, float $avgDuration): string
    {
        return match (true) {
            $totalDuration > 2000 || $avgDuration > 1000 => 'critical',
            $totalDuration > 1000 || $avgDuration > 500 => 'high',
            $totalDuration > 500 || $avgDuration > 200 => 'medium',
            default => 'low'
        };
    }

    private function calculateBottleneckImpact(float $totalDuration, int $count, float $avgDuration): int
    {
        // Impact score based on frequency and duration
        $frequencyWeight = min(100, $count * 2);
        $durationWeight = min(100, $avgDuration / 10);

        return (int) min(100, ($frequencyWeight + $durationWeight) / 2);
    }

    private function calculatePriorityScore(string $severity, int $impact): int
    {
        $severityMultiplier = match ($severity) {
            'critical' => 4,
            'high' => 3,
            'medium' => 2,
            default => 1
        };

        return min(100, $impact * $severityMultiplier);
    }

    private function generateRecommendations($metric): array
    {
        $recommendations = [];
        $key = $metric->key;
        $category = $metric->category->value;
        $avgDuration = $metric->measurements['avg_duration_ms'] ?? 0;

        switch ($category) {
            case 'database':
                if ($avgDuration > 100) {
                    $recommendations[] = 'Add database indexes for frequently queried columns';
                    $recommendations[] = 'Review and optimize complex joins';
                    $recommendations[] = 'Consider query result caching';
                }
                if (str_contains($key, 'findBy')) {
                    $recommendations[] = 'Implement repository-level caching';
                }

                break;

            case 'controller':
                if ($avgDuration > 200) {
                    $recommendations[] = 'Move business logic to service classes';
                    $recommendations[] = 'Consider async processing for heavy operations';
                    $recommendations[] = 'Implement request-response caching';
                }

                break;

            case 'view':
                if (str_contains($key, 'dom_parsing')) {
                    $recommendations[] = 'Enable view caching';
                    $recommendations[] = 'Optimize template complexity';
                }
                if ($avgDuration > 50) {
                    $recommendations[] = 'Consider static HTML generation';
                }

                break;

            case 'cache':
                if ($avgDuration > 10) {
                    $recommendations[] = 'Optimize cache key structure';
                    $recommendations[] = 'Check cache backend performance';
                }

                break;

            default:
                if ($avgDuration > 100) {
                    $recommendations[] = 'Profile operation to identify bottlenecks';
                    $recommendations[] = 'Consider performance monitoring';
                }
        }

        return $recommendations;
    }

    private function estimateImprovementPotential($metric): array
    {
        $avgDuration = $metric->measurements['avg_duration_ms'] ?? 0;
        $category = $metric->category->value;

        $potentialImprovement = match ($category) {
            'database' => min(80, $avgDuration * 0.6),
            'controller' => min(70, $avgDuration * 0.5),
            'view' => min(90, $avgDuration * 0.7),
            'cache' => min(60, $avgDuration * 0.4),
            default => min(50, $avgDuration * 0.3)
        };

        return [
            'estimated_improvement_ms' => round($potentialImprovement, 2),
            'improvement_percentage' => round(($potentialImprovement / max(1, $avgDuration)) * 100, 1),
            'confidence' => $this->getImprovementConfidence($category, $avgDuration),
        ];
    }

    private function getImprovementConfidence(string $category, float $avgDuration): string
    {
        return match (true) {
            $category === 'database' && $avgDuration > 200 => 'high',
            $category === 'view' && $avgDuration > 100 => 'high',
            $avgDuration > 500 => 'medium',
            default => 'low'
        };
    }

    private function calculateOptimizationPotential(array $bottlenecks): array
    {
        if (empty($bottlenecks)) {
            return ['total_potential_ms' => 0, 'confidence' => 'low'];
        }

        $totalPotential = 0;
        foreach ($bottlenecks as $bottleneck) {
            $improvement = $bottleneck['estimated_improvement']['estimated_improvement_ms'] ?? 0;
            $totalPotential += $improvement;
        }

        return [
            'total_potential_ms' => round($totalPotential, 2),
            'average_per_bottleneck_ms' => round($totalPotential / count($bottlenecks), 2),
            'confidence' => count($bottlenecks) > 5 ? 'high' : 'medium',
        ];
    }

    private function calculateOverallHealth(array $requestStats, array $bottlenecks): array
    {
        $score = 100;
        $issues = [];

        // Request time analysis
        $requestTime = $requestStats['time_ms'] ?? 0;
        if ($requestTime > 1000) {
            $score -= 30;
            $issues[] = 'Request time over 1 second';
        } elseif ($requestTime > 500) {
            $score -= 15;
            $issues[] = 'Request time over 500ms';
        } elseif ($requestTime > 200) {
            $score -= 5;
            $issues[] = 'Request time over 200ms';
        }

        // Memory usage analysis
        $memoryMB = ($requestStats['memory_bytes'] ?? 0) / 1024 / 1024;
        if ($memoryMB > 128) {
            $score -= 20;
            $issues[] = 'High memory usage (> 128MB)';
        } elseif ($memoryMB > 64) {
            $score -= 10;
            $issues[] = 'Moderate memory usage (> 64MB)';
        }

        // Bottleneck analysis
        $criticalBottlenecks = array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical');
        $highBottlenecks = array_filter($bottlenecks, fn ($b) => $b['severity'] === 'high');

        $score -= count($criticalBottlenecks) * 25;
        $score -= count($highBottlenecks) * 10;

        if (count($criticalBottlenecks) > 0) {
            $issues[] = count($criticalBottlenecks) . ' critical performance issues';
        }
        if (count($highBottlenecks) > 0) {
            $issues[] = count($highBottlenecks) . ' high-impact performance issues';
        }

        $score = max(0, min(100, $score));

        return [
            'score' => $score,
            'status' => $this->getHealthStatus($score),
            'issues' => $issues,
            'request_time_ms' => $requestTime,
            'memory_usage_mb' => round($memoryMB, 2),
            'bottlenecks_count' => count($bottlenecks),
            'critical_issues' => count($criticalBottlenecks),
            'health_trend' => $this->calculateHealthTrend($score),
        ];
    }

    private function calculateHealthTrend(int $score): string
    {
        // Simplified trend calculation
        return match (true) {
            $score >= 80 => 'stable',
            $score >= 60 => 'declining',
            default => 'critical'
        };
    }

    private function generateExecutiveRecommendations(array $overallHealth, array $bottlenecks): array
    {
        $recommendations = [];

        if ($overallHealth['score'] < 70) {
            $recommendations[] = 'Immediate performance optimization required';
        }

        $criticalCount = count(array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical'));
        if ($criticalCount > 0) {
            $recommendations[] = "Address {$criticalCount} critical performance bottlenecks";
        }

        if ($overallHealth['memory_usage_mb'] > 100) {
            $recommendations[] = 'Investigate and optimize memory usage';
        }

        if (empty($recommendations)) {
            $recommendations[] = 'Continue monitoring performance metrics';
        }

        return $recommendations;
    }

    private function getImmediateActions(array $bottlenecks): array
    {
        $criticalBottlenecks = array_filter($bottlenecks, fn ($b) => $b['severity'] === 'critical');

        $actions = [];
        foreach (array_slice($criticalBottlenecks, 0, 3) as $bottleneck) {
            $actions[] = [
                'action' => 'Optimize ' . $bottleneck['key'],
                'priority' => 'critical',
                'estimated_effort' => 'high',
                'expected_impact' => $bottleneck['estimated_improvement']['improvement_percentage'] . '% improvement',
            ];
        }

        return $actions;
    }

    private function getOptimizationRoadmap(array $bottlenecks): array
    {
        $roadmap = [];
        $categories = [];

        foreach ($bottlenecks as $bottleneck) {
            $category = $bottleneck['category'];
            if (! isset($categories[$category])) {
                $categories[$category] = [];
            }
            $categories[$category][] = $bottleneck;
        }

        foreach ($categories as $category => $categoryBottlenecks) {
            $roadmap[] = [
                'phase' => ucfirst($category) . ' optimization',
                'timeline' => '1-2 weeks',
                'bottlenecks_count' => count($categoryBottlenecks),
                'estimated_improvement' => $this->calculateCategoryImprovement($categoryBottlenecks),
            ];
        }

        return $roadmap;
    }

    private function calculateCategoryImprovement(array $categoryBottlenecks): string
    {
        $totalImprovement = 0;
        foreach ($categoryBottlenecks as $bottleneck) {
            $totalImprovement += $bottleneck['estimated_improvement']['improvement_percentage'] ?? 0;
        }

        $avgImprovement = count($categoryBottlenecks) > 0 ? $totalImprovement / count($categoryBottlenecks) : 0;

        return round($avgImprovement, 1) . '% average improvement';
    }

    private function getMonitoringRecommendations(array $overallHealth): array
    {
        $recommendations = [];

        if ($overallHealth['score'] < 80) {
            $recommendations[] = 'Increase monitoring frequency for performance metrics';
        }

        $recommendations[] = 'Set up alerts for response times > 500ms';
        $recommendations[] = 'Monitor memory usage trends';
        $recommendations[] = 'Track performance regression after deployments';

        return $recommendations;
    }

    private function calculateConfidenceScore(array $bottlenecks): int
    {
        $dataPoints = count($bottlenecks);

        return match (true) {
            $dataPoints > 10 => 95,
            $dataPoints > 5 => 80,
            $dataPoints > 2 => 65,
            default => 50
        };
    }
}
