<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\DocumentVersion;
use App\Entity\User;
use App\Service\IngestOrchestrator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'mto:agent:ingest:version')]
class KnowledgeIngestCommand extends Command
{
    public function __construct(
        private readonly IngestOrchestrator $orchestrator,
        private readonly EntityManagerInterface $em,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('versionId', InputArgument::REQUIRED, 'UUID of DocumentVersion')
            ->addArgument('userId', InputArgument::REQUIRED, 'UUID of user triggering ingest');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $versionId = (string) $input->getArgument('versionId');
        $userId    = (string) $input->getArgument('userId');

        $version = $this->em->getRepository(DocumentVersion::class)->find($versionId);
        $user    = $this->em->getRepository(User::class)->find($userId);

        if (!$version || !$user) {
            $output->writeln('<error>Version or User not found.</error>');
            return Command::FAILURE;
        }

        $output->writeln('Starting ingest...');

        $job = $this->orchestrator->runForVersion($version, $user);

        $output->writeln(sprintf('<info>Ingest completed. Job: %s</info>', (string) $job->getId()));

        return Command::SUCCESS;
    }
}
