<?php

namespace App\Livewire;

use App\AI\Agents\MediaBuyingAgent;
use Livewire\Attributes\Title;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Throwable;

#[Title('Media Buying Assistant')]
class AgentChat extends Component
{
    /**
     * The raw API conversation, replayed into a fresh agent each turn.
     * The agent itself is not serializable, its history is.
     */
    public array $history = [];

    /**
     * What we render: ['role' => user|assistant|error, 'text' => ..., 'tools' => []].
     */
    public array $messages = [];

    #[Validate('required|string|max:2000')]
    public string $prompt = '';

    public function send(): void
    {
        $this->validate();

        // A single turn can run several tools against the Meta Ads API.
        set_time_limit(600);

        $prompt = $this->prompt;
        $this->prompt = '';

        $this->messages[] = ['role' => 'user', 'text' => $prompt, 'tools' => []];

        $agent = new MediaBuyingAgent;
        $agent->history = $this->history;

        try {
            $reply = $agent->prompt($prompt);
        } catch (Throwable $e) {
            $this->messages[] = ['role' => 'error', 'text' => $e->getMessage(), 'tools' => []];

            return;
        }

        $this->history = $agent->history;

        $this->messages[] = [
            'role' => 'assistant',
            'text' => $reply,
            'tools' => $agent->toolCalls,
        ];
    }

    public function clearConversation(): void
    {
        $this->history = [];
        $this->messages = [];
    }

    public function render()
    {
        return view('livewire.agent-chat');
    }
}
