<?php

declare(strict_types=1);

namespace App\Command;

use App\Tag\TagVectorIndexHealthService;
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:tag:health',
    description: 'Health-Check für Tag-/FAISS-Konsistenz'
)]
final class TagHealthCheckCommand extends Command
{
    public function __construct(
        private readonly TagVectorIndexHealthService $health
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addOption(
            'summary',
            null,
            InputOption::VALUE_NONE,
            'Gibt eine lesbare Zusammenfassung statt JSON aus.'
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $result = $this->health->check();
        $status = trim((string) ($result['status'] ?? ''));

        if ($status === '') {
            $status = 'UNKNOWN';
            $result['status'] = $status;
            $result['error'] = 'Health service returned no status.';
        }

        if ((bool) $input->getOption('summary')) {
            $this->renderSummary(new SymfonyStyle($input, $output), $result);
        } else {
            $this->renderJson($output, $result);
        }

        return $this->isHealthy($status)
            ? Command::SUCCESS
            : Command::FAILURE;
    }

    /**
     * @param array<string, mixed> $result
     */
    private function renderSummary(SymfonyStyle $io, array $result): void
    {
        $io->title('Tag Vector Health');

        $io->definitionList(
            ['status' => (string) ($result['status'] ?? 'UNKNOWN')],
            ['tags_ndjson_exists' => !empty($result['tags_ndjson_exists']) ? 'yes' : 'no'],
            ['tags_ndjson_count' => (string) ($result['tags_ndjson_count'] ?? 0)],
            ['vector_exists' => !empty($result['vector_exists']) ? 'yes' : 'no'],
            ['meta_exists' => !empty($result['meta_exists']) ? 'yes' : 'no'],
            ['vector_tag_count' => (string) ($result['vector_tag_count'] ?? 0)],
            ['meta_valid' => !empty($result['meta_valid']) ? 'yes' : 'no'],
            ['tags_with_active_document_ids' => (string) ($result['tags_with_active_document_ids'] ?? 0)],
        );

        if (!empty($result['error'])) {
            $io->warning((string) $result['error']);
        }
    }

    /**
     * @param array<string, mixed> $result
     */
    private function renderJson(OutputInterface $output, array $result): void
    {
        $json = json_encode(
            $result,
            JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );

        if (!is_string($json)) {
            $json = json_encode([
                'status' => 'UNKNOWN',
                'error' => 'json_encode_failed',
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            if (!is_string($json)) {
                $json = "{\"status\":\"UNKNOWN\",\"error\":\"json_encode_failed\"}";
            }
        }

        $output->writeln($json);
    }

    private function isHealthy(string $status): bool
    {
        return in_array($status, ['OK', 'OK_EMPTY'], true);
    }
}