<?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:config:validate',
    description: 'Validate the effective RetrieX configuration'
)]
final class ConfigValidateCommand extends Command
{
    public function __construct(
        private readonly RetriexEffectiveConfigProvider $provider,
    ) {
        parent::__construct();
    }

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

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

        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, errors:list<string>, warnings:list<string>, config:array<string,mixed>} $result
     */
    private function renderSummary(SymfonyStyle $io, array $result): void
    {
        $io->title('RetrieX configuration validation');

        if ($result['errors'] === [] && $result['warnings'] === []) {
            $io->success('Configuration is valid.');
            return;
        }

        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);
            }
        }
    }
}
