<?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\Alerting\AlertManager;

/**
 * Console commands for alert management
 */
final readonly class AlertCommand
{
    public function __construct(
        private AlertManager $alertManager
    ) {
    }

    #[ConsoleCommand(
        name: 'alerts:test',
        description: 'Test all configured alert channels'
    )]
    public function test(ConsoleInput $input, ConsoleOutput $output): int
    {
        $output->writeLine('<info>Testing alert channels...</info>');
        $output->writeLine('');

        $results = $this->alertManager->testChannels();

        $allPassed = true;

        foreach ($results as $channel => $result) {
            $statusIcon = match ($result['status']) {
                'ok' => '✅',
                'failed' => '❌',
                'error' => '💥',
                default => '❓',
            };

            $output->writeLine("{$statusIcon} <comment>{$channel}</comment>: {$result['status']}");

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

            $output->writeLine("  <comment>Tested at:</comment> {$result['test_time']}");
            $output->writeLine('');

            if ($result['status'] !== 'ok') {
                $allPassed = false;
            }
        }

        if ($allPassed) {
            $output->writeLine('<info>All alert channels are working correctly!</info>');

            return ExitCode::SUCCESS;
        } else {
            $output->writeLine('<error>Some alert channels have issues. Please check the configuration.</error>');

            return ExitCode::FAILURE;
        }
    }

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

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

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

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

        $output->writeLine('<comment>Configured Channels:</comment>');
        foreach ($stats['channels'] as $channel) {
            $output->writeLine("  • {$channel}");
        }
        $output->writeLine('');

        $output->writeLine('<comment>Urgency Mapping:</comment>');
        foreach ($stats['urgency_mapping'] as $urgency => $channels) {
            $urgencyIcon = match ($urgency) {
                'urgent' => '🚨',
                'high' => '⚠️',
                'medium' => 'ℹ️',
                'low' => '📝',
                default => '❓',
            };

            $output->writeLine("  {$urgencyIcon} <comment>{$urgency}:</comment> " . implode(', ', $channels));
        }

        return ExitCode::SUCCESS;
    }
}
