<?php

declare(strict_types=1);

namespace App\Command;

use App\Agent\AgentRunner;
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;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * AgentCliCommand
 *
 * Interactive CLI interface for the AI agent.
 * Symfony-native, streaming-first implementation.
 *
 * Responsibilities:
 * - Read user input from STDIN
 * - Stream tokens from the AgentRunner
 * - Render streamed output to the terminal
 *
 * The AgentRunner is the single owner of:
 * - Think suppression
 * - Context handling
 * - Streaming semantics
 */
#[AsCommand(
    name: 'mto:agent:chat',
    description: 'Start an interactive CLI chat with the AI agent'
)]
final class AgentCliCommand extends Command
{
    public function __construct(
        private readonly AgentRunner $agentRunner,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('user-id', InputArgument::OPTIONAL, 'User/session identifier', 'cli');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $userId = (string) $input->getArgument('user-id');

        $io->success('AI Agent CLI started. Press Ctrl+C or type "exit" to quit.');
        $io->writeln('');

        while (true) {
            $prompt = $io->ask('Question');

            if ($prompt === null) {
                // EOF (e.g. piped input ended)
                $io->writeln('');
                return Command::SUCCESS;
            }

            $prompt = trim($prompt);

            if ($prompt === '' || strtolower($prompt) === 'exit') {
                $io->writeln('');
                return Command::SUCCESS;
            }

            $io->writeln('');
            $io->writeln('<info>Answer:</info>');

            foreach ($this->agentRunner->run($prompt, $userId) as $token) {
                $output->write($token);
            }

            $io->writeln('');
            $io->writeln('');
        }
    }
}
