<?php

declare(strict_types=1);

namespace App\Command;

use App\Tag\TagNdjsonExporter;
use App\Tag\TagVectorIndexBuilder;
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:rebuild',
    description: 'Export tags.ndjson and rebuild tag vector index (vector_tags.index)'
)]
final class TagsRebuildCommand extends Command
{
    public function __construct(
        private readonly TagNdjsonExporter $exporter,
        private readonly TagVectorIndexBuilder $builder,
    ) {
        parent::__construct();
    }

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

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

            $io->writeln('<info>1/2 Exported tags.ndjson</info>');
            $io->writeln('Path:  ' . (string) ($export['path'] ?? ''));
            $io->writeln('Tags:  ' . (string) ($export['tags'] ?? 0));
            $io->writeln('Lines: ' . (string) ($export['lines'] ?? 0));
            $io->writeln('Bytes: ' . (string) ($export['bytes'] ?? 0));
            $io->newLine();
            $io->writeln('<comment>2/2 Building vector_tags.index</comment>');
            $io->writeln('If this step fails, check the embedding model cache or set RETRIEX_EMBEDDING_MODEL_PATH.');

            $this->builder->build();

            $io->success('Tag rebuild completed.');

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

            if ($output->isVerbose() && $e->getPrevious() !== null) {
                $io->writeln('<comment>Previous exception:</comment> ' . $e->getPrevious()->getMessage());
            }

            return Command::FAILURE;
        }
    }

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

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

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

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