<?php

declare(strict_types=1);

namespace App\Framework\Database\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ConsoleStyle;
use App\Framework\Console\ExitCode;
use App\Framework\Database\DatabaseManager;
use App\Framework\Database\EntityManager;
use App\Framework\Database\Profiling\ProfilingDashboard;

final class ShowProfilingStatsCommand
{
    public function __construct(
        private DatabaseManager $databaseManager,
        private EntityManager $entityManager
    ) {
    }

    #[ConsoleCommand(name: 'db:profiling:stats', description: 'Show database profiling statistics and reports')]
    public function execute(ConsoleInput $input, ConsoleOutput $output): ExitCode
    {
        $output->writeLine("🔍 Database Profiling Statistics\n", ConsoleStyle::info());

        // Check if profiling is enabled
        if (! $this->databaseManager->isProfilingEnabled()) {
            $output->writeLine("⚠️  Database profiling is not enabled", ConsoleStyle::warning());
            $output->writeLine("Enable it in your configuration to see detailed statistics\n");

            return ExitCode::SUCCESS;
        }

        // Create profiling dashboard
        $dashboard = new ProfilingDashboard();

        // Register database manager with dashboard
        $this->databaseManager->registerWithProfilingDashboard($dashboard, 'main');

        // Get overview
        $overview = $dashboard->getOverview();

        $output->writeLine("📊 Overview:");
        $output->writeLine("  Total Connections: " . $overview['total_connections']);
        $output->writeLine("  Total Queries: " . $overview['global_stats']['total_queries']);
        $output->writeLine("  Slow Queries: " . $overview['global_stats']['total_slow_queries']);
        $output->writeLine("  Slow Query %: " . round($overview['global_stats']['slow_query_percentage'], 2) . "%");
        $output->writeLine("  Avg Execution Time: " . round($overview['global_stats']['average_execution_time_ms'], 2) . " ms\n");

        // Show connection details
        foreach ($overview['connections'] as $name => $conn) {
            $statusColor = match($conn['performance_assessment']) {
                'excellent', 'good' => ConsoleStyle::success(),
                'fair', 'moderate' => ConsoleStyle::warning(),
                default => ConsoleStyle::error()
            };

            $output->writeLine("🔗 Connection: {$name}", ConsoleStyle::info());
            $output->writeLine("  Status: " . ucfirst($conn['performance_assessment']), $statusColor);
            $output->writeLine("  Queries: {$conn['queries_count']}");
            $output->writeLine("  Slow Queries: {$conn['slow_queries_count']} ({$conn['slow_query_percentage']})");
            $output->writeLine("  Avg Time: " . round($conn['average_execution_time_ms'], 2) . " ms");
            $output->writeLine("  Profiling Active: " . ($conn['enabled'] ? '✅' : '❌') . "\n");
        }

        // Show performance report
        try {
            $performanceReport = $dashboard->getPerformanceReport();
            $metrics = $performanceReport->getOverallMetrics();

            $output->writeLine("⚡ Performance Metrics:");
            $output->writeLine("  Total Execution Time: " . round($metrics['total_execution_time_ms'], 2) . " ms");
            $output->writeLine("  Average Query Time: " . round($metrics['average_execution_time_ms'], 2) . " ms\n");

            $trends = $performanceReport->getPerformanceTrends();
            foreach ($trends as $connectionName => $trend) {
                $trendColor = match($trend['trend']) {
                    'excellent', 'improving' => ConsoleStyle::success(),
                    'stable' => ConsoleStyle::info(),
                    'declining' => ConsoleStyle::warning(),
                    'critical' => ConsoleStyle::error()
                };

                $output->writeLine("📈 {$connectionName} Trend: " . ucfirst($trend['trend']), $trendColor);

                if (! empty($trend['recommendations'])) {
                    foreach ($trend['recommendations'] as $recommendation) {
                        $output->writeLine("  💡 {$recommendation}", ConsoleStyle::dim());
                    }
                }
            }
        } catch (\Exception $e) {
            $output->writeLine("⚠️  Could not generate performance report: " . $e->getMessage(), ConsoleStyle::warning());
        }

        // Show slow query report if there are slow queries
        try {
            $slowQueryReport = $dashboard->getSlowQueryReport();
            $slowQueries = $slowQueryReport->getTopSlowQueries(5);

            if (! empty($slowQueries)) {
                $output->writeLine("\n🐌 Top 5 Slow Queries:");

                foreach ($slowQueries as $index => $entry) {
                    $profile = $entry['profile'];
                    $connection = $entry['connection'];

                    $output->writeLine("  " . ($index + 1) . ". [{$connection}] " . round($profile->executionTime->toMilliseconds(), 2) . " ms");
                    $output->writeLine("     " . substr($profile->sql, 0, 80) . "...", ConsoleStyle::dim());
                }
            }
        } catch (\Exception $e) {
            $output->writeLine("⚠️  Could not generate slow query report: " . $e->getMessage(), ConsoleStyle::warning());
        }

        // Show optimization suggestions
        try {
            $optimizationReport = $dashboard->getOptimizationReport();
            $summary = $optimizationReport->getOptimizationSummary();

            if ($summary['critical_issues'] > 0 || $summary['total_issues'] > 0) {
                $output->writeLine("\n🔧 Optimization Summary:");
                $output->writeLine("  Total Issues: " . $summary['total_issues']);
                $output->writeLine("  Critical Issues: " . $summary['critical_issues']);

                if (! empty($summary['top_recommendations'])) {
                    $output->writeLine("\n💡 Top Recommendations:");
                    $count = 0;
                    foreach ($summary['top_recommendations'] as $rec) {
                        if (++$count > 3) {
                            break;
                        }
                        $output->writeLine("  • " . $rec['text'] . " (affects " . $rec['count'] . " connection(s))", ConsoleStyle::info());
                    }
                }
            } else {
                $output->writeLine("\n✅ No critical performance issues detected!", ConsoleStyle::success());
            }
        } catch (\Exception $e) {
            $output->writeLine("⚠️  Could not generate optimization report: " . $e->getMessage(), ConsoleStyle::warning());
        }

        $output->writeLine("\n💡 Tip: Use 'db:profiling:clear' to clear profiling data", ConsoleStyle::dim());
        $output->writeLine("💡 Tip: Use 'db:profiling:export --format=html > report.html' to export detailed reports", ConsoleStyle::dim());

        return ExitCode::SUCCESS;
    }
}
