<?php

declare(strict_types=1);

namespace App\Command;

use App\Tag\TagNdjsonExporter;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'mto:agent:tags:export',
    description: 'Export tags to NDJSON for tag vector routing'
)]
final class TagsExportCommand extends Command
{
    public function __construct(
        private readonly TagNdjsonExporter $exporter,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        try {
            $result = $this->exporter->export();
            $this->assertValidExport($result);

            $io->writeln('<info>Tags NDJSON exported</info>');
            $io->writeln('Path:  ' . (string) ($result['path'] ?? ''));
            $io->writeln('Tags:  ' . (string) ($result['tags'] ?? 0));
            $io->writeln('Lines: ' . (string) ($result['lines'] ?? 0));
            $io->writeln('Bytes: ' . (string) ($result['bytes'] ?? 0));
            $io->success('Tag export completed.');

            return Command::SUCCESS;
        } catch (\Throwable $e) {
            $io->error($e->getMessage());

            return Command::FAILURE;
        }
    }

    /**
     * @param array<string, mixed> $result
     */
    private function assertValidExport(array $result): void
    {
        $path = trim((string) ($result['path'] ?? ''));

        if ($path === '' || !is_file($path)) {
            throw new \RuntimeException('Tag export failed: tags.ndjson is missing.');
        }

        $tags = (int) ($result['tags'] ?? 0);
        $lines = (int) ($result['lines'] ?? 0);
        $bytes = (int) ($result['bytes'] ?? 0);

        if ($tags < 0 || $lines < 0 || $bytes < 0) {
            throw new \RuntimeException('Tag export returned invalid statistics.');
        }
    }
}