<?php

declare(strict_types=1);

namespace App\Command;

use App\Config\RetriexEffectiveConfigProvider;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'mto:agent:regression:test',
    description: 'Run offline regression guards for stable RetrieX configuration paths'
)]
final class RegressionBaselineCommand extends Command
{
    public function __construct(
        private readonly RetriexEffectiveConfigProvider $provider,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption('json', null, InputOption::VALUE_NONE, 'Render regression result as JSON.');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $result = $this->provider->regressionBaseline();

        if ((bool) $input->getOption('json')) {
            $json = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $output->writeln(is_string($json) ? $json : '{}');

            return $result['status'] === 'OK' ? Command::SUCCESS : Command::FAILURE;
        }

        $this->renderSummary(new SymfonyStyle($input, $output), $result);

        return $result['status'] === 'OK' ? Command::SUCCESS : Command::FAILURE;
    }

    /**
     * @param array{status:string, checks:array<string,bool>, errors:list<string>, warnings:list<string>} $result
     */
    private function renderSummary(SymfonyStyle $io, array $result): void
    {
        $io->title('RetrieX regression baseline');

        $rows = [];
        foreach ($result['checks'] as $name => $passed) {
            $rows[] = [$name, $passed ? 'OK' : 'FAILED'];
        }

        if ($rows !== []) {
            $io->table(['Check', 'Result'], $rows);
        }

        if ($result['errors'] !== []) {
            $io->section('Errors');
            foreach ($result['errors'] as $error) {
                $io->writeln('- ' . $error);
            }
        }

        if ($result['warnings'] !== []) {
            $io->section('Warnings');
            foreach ($result['warnings'] as $warning) {
                $io->writeln('- ' . $warning);
            }
        }

        if ($result['status'] === 'OK') {
            $io->success('Regression baseline checks passed.');
        } else {
            $io->error('Regression baseline checks failed.');
        }
    }
}
