<?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;

/**
 * Console commands for error pattern management
 */
final readonly class ErrorPatternsCommand
{
    public function __construct(
        private ErrorAggregator $errorAggregator
    ) {
    }

    #[ConsoleCommand(
        name: 'error-patterns:list',
        description: 'List active error patterns'
    )]
    public function list(ConsoleInput $input, ConsoleOutput $output): int
    {
        $args = $input->getArguments();
        $service = $args[0] ?? null;
        $limit = (int) ($args[1] ?? 20);

        if ($service) {
            $patterns = $this->errorAggregator->getPatternsByService($service, $limit);
            $output->writeLine("<info>Error Patterns for service: {$service}</info>");
        } else {
            $patterns = $this->errorAggregator->getActivePatterns($limit);
            $output->writeLine('<info>Active Error Patterns</info>');
        }

        $output->writeLine('');

        if (empty($patterns)) {
            $output->writeLine('<comment>No patterns found</comment>');

            return ExitCode::SUCCESS;
        }

        foreach ($patterns as $pattern) {
            $icon = $pattern->severity->getIcon();
            $status = $pattern->isAcknowledged ? '✅' : ($pattern->isCriticalPattern() ? '🚨' : '⚠️');

            $output->writeLine(sprintf(
                "%s <comment>%s</comment> [%s] %s.%s.%s",
                $icon,
                $pattern->id->toString(),
                $status,
                $pattern->service,
                $pattern->component,
                $pattern->operation
            ));

            $output->writeLine("    Message: {$pattern->normalizedMessage}");
            $output->writeLine(sprintf(
                "    Count: <comment>%d</comment> | Frequency: <comment>%.1f/min</comment> | Users: <comment>%d</comment>",
                $pattern->occurrenceCount,
                $pattern->getFrequency(),
                count($pattern->affectedUsers)
            ));

            $output->writeLine(sprintf(
                "    First: %s | Last: %s",
                $pattern->firstOccurrence->format('M j H:i'),
                $pattern->lastOccurrence->format('M j H:i')
            ));

            if ($pattern->isAcknowledged) {
                $output->writeLine("    <info>Acknowledged by: {$pattern->acknowledgedBy} at {$pattern->acknowledgedAt->format('M j H:i')}</info>");
                if ($pattern->resolution) {
                    $output->writeLine("    Resolution: {$pattern->resolution}");
                }
            }

            $output->writeLine('');
        }

        return ExitCode::SUCCESS;
    }

    #[ConsoleCommand(
        name: 'error-patterns:acknowledge',
        description: 'Acknowledge an error pattern'
    )]
    public function acknowledge(ConsoleInput $input, ConsoleOutput $output): int
    {
        $args = $input->getArguments();
        $patternId = $args[0] ?? null;
        $acknowledgedBy = $args[1] ?? 'console';
        $resolution = $args[2] ?? null;

        if (! $patternId) {
            $output->writeLine('<error>Pattern ID is required</error>');
            $output->writeLine('Usage: error-patterns:acknowledge <pattern-id> [acknowledged-by] [resolution]');

            return ExitCode::FAILURE;
        }

        $success = $this->errorAggregator->acknowledgePattern($patternId, $acknowledgedBy, $resolution);

        if ($success) {
            $output->writeLine("<info>Pattern {$patternId} acknowledged successfully</info>");

            return ExitCode::SUCCESS;
        } else {
            $output->writeLine("<error>Failed to acknowledge pattern {$patternId} (pattern not found)</error>");

            return ExitCode::FAILURE;
        }
    }

    #[ConsoleCommand(
        name: 'error-patterns:resolve',
        description: 'Resolve an error pattern'
    )]
    public function resolve(ConsoleInput $input, ConsoleOutput $output): int
    {
        $args = $input->getArguments();
        $patternId = $args[0] ?? null;
        $resolution = $args[1] ?? null;

        if (! $patternId) {
            $output->writeLine('<error>Pattern ID is required</error>');
            $output->writeLine('Usage: error-patterns:resolve <pattern-id> <resolution>');

            return ExitCode::FAILURE;
        }

        if (! $resolution) {
            $output->writeLine('<error>Resolution description is required</error>');
            $output->writeLine('Usage: error-patterns:resolve <pattern-id> <resolution>');

            return ExitCode::FAILURE;
        }

        $success = $this->errorAggregator->resolvePattern($patternId, $resolution);

        if ($success) {
            $output->writeLine("<info>Pattern {$patternId} resolved successfully</info>");

            return ExitCode::SUCCESS;
        } else {
            $output->writeLine("<error>Failed to resolve pattern {$patternId} (pattern not found)</error>");

            return ExitCode::FAILURE;
        }
    }
}
