<?php

namespace App\Console\Commands;

use App\AI\Agents\MediaBuyingAgent;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

use function Laravel\Prompts\info;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\text;

#[Signature('agent {question? : Ask once and exit, instead of chatting}')]
#[Description('AI media buying assistant backed by the Meta Ads MCP server')]
class AgentCommand extends Command
{
    public function handle(): int
    {
        // Outside the loop, so the agent keeps its history between turns.
        $agent = new MediaBuyingAgent;

        $once = $this->argument('question');

        while (true) {
            $prompt = $once ?: text('What is on your mind?', required: true);

            if (in_array(strtolower(trim((string) $prompt)), ['exit', 'quit'], true)) {
                return self::SUCCESS;
            }

            $response = $once
                ? $agent->prompt($prompt)
                : spin(fn () => $agent->prompt($prompt), 'Thinking about that');

            foreach ($agent->toolCalls as $tool) {
                $this->line("  <fg=gray>→ {$tool}</>");
            }

            info($response);

            if ($once) {
                return self::SUCCESS;
            }
        }
    }
}
