<?php

declare(strict_types=1);

namespace App\Framework\ErrorAggregation\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ExitCode;
use App\Framework\ErrorAggregation\ErrorAggregator;
use App\Framework\Exception\Core\ErrorSeverity;

/**
 * Console command for error aggregation statistics
 */
final readonly class ErrorAggregationStatsCommand
{
    public function __construct(
        private ErrorAggregator $errorAggregator
    ) {
    }

    #[ConsoleCommand(
        name: 'error-aggregation:stats',
        description: 'Show error aggregation statistics'
    )]
    public function stats(ConsoleInput $input, ConsoleOutput $output): int
    {
        $hours = (int) ($input->getArguments()[0] ?? 24);

        $from = (new \DateTimeImmutable())->sub(new \DateInterval("PT{$hours}H"));
        $to = new \DateTimeImmutable();

        $stats = $this->errorAggregator->getStatistics($from, $to);

        $output->writeLine("<info>Error Aggregation Statistics (last {$hours} hours)</info>");
        $output->writeLine('');

        $output->writeLine(sprintf('📊 <comment>Total Events:</comment> %d', $stats['total_events'] ?? 0));
        $output->writeLine(sprintf('🏢 <comment>Services Affected:</comment> %d', $stats['services_affected'] ?? 0));
        $output->writeLine(sprintf('👥 <comment>Users Affected:</comment> %d', $stats['users_affected'] ?? 0));
        $output->writeLine(sprintf('🌐 <comment>IPs Affected:</comment> %d', $stats['ips_affected'] ?? 0));
        $output->writeLine('');

        if (! empty($stats['by_severity'])) {
            $output->writeLine('<comment>By Severity:</comment>');
            foreach ($stats['by_severity'] as $severity => $count) {
                $severityEnum = ErrorSeverity::from($severity);
                $icon = $severityEnum->getIcon();
                $output->writeLine("  {$icon} {$severity}: {$count}");
            }
            $output->writeLine('');
        }

        // Active patterns
        $activePatterns = $this->errorAggregator->getActivePatterns(10);

        if (! empty($activePatterns)) {
            $output->writeLine('<comment>Top Active Patterns:</comment>');
            foreach ($activePatterns as $pattern) {
                $icon = $pattern->severity->getIcon();
                $status = $pattern->isAcknowledged ? '✅ ACK' : '⚠️ NEW';

                $output->writeLine(sprintf(
                    "  %s [%s] %s.%s (%d occurrences, %.1f/min)",
                    $icon,
                    $status,
                    $pattern->service,
                    $pattern->component,
                    $pattern->occurrenceCount,
                    $pattern->getFrequency()
                ));
            }
        }

        return ExitCode::SUCCESS;
    }

    #[ConsoleCommand(
        name: 'error-aggregation:health',
        description: 'Check error aggregation system health'
    )]
    public function health(ConsoleInput $input, ConsoleOutput $output): int
    {
        $health = $this->errorAggregator->getHealthStatus();

        $output->writeLine('<info>Error Aggregation Health Status</info>');
        $output->writeLine('');

        $statusIcon = $health['status'] === 'healthy' ? '✅' : '❌';
        $output->writeLine("Status: {$statusIcon} {$health['status']}");

        if (isset($health['last_hour_events'])) {
            $output->writeLine("Events (last hour): {$health['last_hour_events']}");
        }

        if (isset($health['active_patterns'])) {
            $output->writeLine("Active patterns: {$health['active_patterns']}");
        }

        if (isset($health['storage_health'])) {
            $storageHealth = $health['storage_health'];
            $storageIcon = $storageHealth['status'] === 'healthy' ? '✅' : '❌';
            $output->writeLine("Storage: {$storageIcon} {$storageHealth['status']}");

            if (isset($storageHealth['event_count'])) {
                $output->writeLine("  Total events: {$storageHealth['event_count']}");
            }

            if (isset($storageHealth['pattern_count'])) {
                $output->writeLine("  Total patterns: {$storageHealth['pattern_count']}");
            }
        }

        if (isset($health['error'])) {
            $output->writeLine("<error>Error: {$health['error']}</error>");
        }

        return $health['status'] === 'healthy' ? ExitCode::SUCCESS : ExitCode::FAILURE;
    }

    #[ConsoleCommand(
        name: 'error-aggregation:cleanup',
        description: 'Clean up old error data based on retention policy'
    )]
    public function cleanup(ConsoleInput $input, ConsoleOutput $output): int
    {
        $output->writeLine('<info>Running error aggregation cleanup...</info>');

        $deletedCount = $this->errorAggregator->cleanup();

        $output->writeLine("<info>Cleanup completed. Deleted {$deletedCount} records.</info>");

        return ExitCode::SUCCESS;
    }
}
