<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\TagRebuildJob;
use App\Tag\TagNdjsonExporter;
use App\Tag\TagVectorIndexBuilder;
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\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'mto:agent:tags:job:run',
    description: 'Run a tag rebuild job (export tags.ndjson + build vector_tags.index) with lock'
)]
final class TagRebuildRunJobCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly TagNdjsonExporter $exporter,
        private readonly TagVectorIndexBuilder $builder,
        private readonly string $lockFilePath,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('jobId', InputArgument::OPTIONAL, 'Existing TagRebuildJob UUID')
            ->addOption('create', null, InputOption::VALUE_NONE, 'Create and immediately run a new TagRebuildJob');
    }

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

        $jobId = trim((string) $input->getArgument('jobId'));
        $create = (bool) $input->getOption('create');

        if (!$create && $jobId === '') {
            $io->error('You must provide either a jobId or use --create.');

            return Command::FAILURE;
        }

        if ($create && $jobId !== '') {
            $io->error('Use either jobId OR --create, not both.');

            return Command::FAILURE;
        }

        $job = null;
        $lockHandle = null;

        try {
            $job = $create ? $this->createJob($io) : $this->findJob($jobId);
            $lockHandle = $this->acquireLock();

            $job->markRunning();
            $this->em->flush();

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

            $io->writeln('<info>tags.ndjson exported</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));

            $this->builder->build();

            $job->markCompleted();
            $this->em->flush();

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

            return Command::SUCCESS;
        } catch (\Throwable $e) {
            if ($job instanceof TagRebuildJob) {
                $job->markFailed($this->buildSafeErrorMessage($e));
                $this->em->flush();
            }

            $io->error('FAILED: ' . $e->getMessage());

            return Command::FAILURE;
        } finally {
            $this->releaseLock($lockHandle);
        }
    }

    private function createJob(SymfonyStyle $io): TagRebuildJob
    {
        $job = new TagRebuildJob();
        $this->em->persist($job);
        $this->em->flush();

        $io->writeln('<info>Created new TagRebuildJob: ' . (string) $job->getId() . '</info>');

        return $job;
    }

    private function findJob(string $jobId): TagRebuildJob
    {
        /** @var TagRebuildJob|null $job */
        $job = $this->em->getRepository(TagRebuildJob::class)->find($jobId);

        if (!$job instanceof TagRebuildJob) {
            throw new \RuntimeException('Job not found.');
        }

        return $job;
    }

    /**
     * @return resource
     */
    private function acquireLock()
    {
        $lockDir = \dirname($this->lockFilePath);

        if (!\is_dir($lockDir) && !@\mkdir($lockDir, 0775, true) && !\is_dir($lockDir)) {
            throw new \RuntimeException('Cannot create lock directory.');
        }

        $handle = @\fopen($this->lockFilePath, 'c+');

        if ($handle === false) {
            throw new \RuntimeException('Cannot open lock file: ' . $this->lockFilePath);
        }

        if (!@\flock($handle, LOCK_EX | LOCK_NB)) {
            @\fclose($handle);
            throw new \RuntimeException('Another tag rebuild is currently running (lock busy).');
        }

        return $handle;
    }

    /**
     * @param resource|null $handle
     */
    private function releaseLock($handle): void
    {
        if (!is_resource($handle)) {
            return;
        }

        @\flock($handle, LOCK_UN);
        @\fclose($handle);
    }

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

        if ($path === '' || !\is_file($path)) {
            throw new \RuntimeException('Export failed: NDJSON file missing.');
        }

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

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

    private function buildSafeErrorMessage(\Throwable $e): string
    {
        $message = trim($e->getMessage());

        if ($message === '') {
            return 'Unknown tag rebuild failure.';
        }

        return mb_substr($message, 0, 4000);
    }
}