<?php

namespace App\AI\Agents;

use App\AI\Attributes\CompactsAfter;
use App\AI\Tools\Tool;
use Illuminate\Support\Facades\Http;
use ReflectionClass;

abstract class Agent
{
    /**
     * The conversation so far.
     */
    public array $history = [];

    /**
     * Names of the tools invoked during the most recent prompt(), so a
     * console command or UI can report them. No output concerns in here.
     *
     * @var array<int, string>
     */
    public array $toolCalls = [];

    /**
     * The persona for this agent. Override per agent.
     */
    protected string $persona = 'You are a helpful AI assistant.';

    /**
     * Used when an agent declares no CompactsAfter attribute.
     */
    protected int $defaultThreshold = 30;

    /**
     * Guard against an agent looping on tools forever.
     */
    protected int $maxIterations = 15;

    /**
     * The tools this agent may reach for.
     *
     * @return array<int, Tool>
     */
    protected function tools(): array
    {
        return [];
    }

    /**
     * The JSON schema this agent's final response must conform to.
     * Return an empty array for a plain text response.
     */
    protected function schema(): array
    {
        return [];
    }

    /**
     * Send a prompt and run the agent's inner loop until it can answer.
     */
    public function prompt(string $prompt): string
    {
        $this->maybeCompact();

        $this->toolCalls = [];

        $this->history[] = ['role' => 'user', 'content' => $prompt];

        for ($iteration = 0; $iteration < $this->maxIterations; $iteration++) {
            $response = $this->runModel();

            $this->history = [...$this->history, ...$response['output']];

            $toolCalls = collect($response['output'])
                ->filter(fn (array $item) => $item['type'] === 'function_call');

            // No tools requested means the response is ready.
            if ($toolCalls->isEmpty()) {
                return $this->textFrom($response);
            }

            $toolCalls->each(fn (array $call) => $this->runTool($call));
        }

        return "Stopped after {$this->maxIterations} tool iterations without a final answer.";
    }

    public function messages(): array
    {
        return $this->history;
    }

    /**
     * The full system message: this agent's persona, plus the project
     * guidelines file if one exists.
     *
     * These are sent as `instructions`, never as part of the history, so
     * compaction can never discard them.
     */
    public function instructions(): string
    {
        $instructions = $this->persona;

        if (file_exists($path = base_path('Larry.md'))) {
            $instructions .= "\n\n# Project Guidelines\n\n".file_get_contents($path);
        }

        return $instructions;
    }

    /**
     * Pull the assistant's text out of the response. The first output item is
     * not guaranteed to be the message, so find it rather than assume.
     */
    protected function textFrom(array $response): string
    {
        return collect($response['output'] ?? [])
            ->firstWhere('type', 'message')['content'][0]['text'] ?? '';
    }

    protected function maybeCompact(): void
    {
        if ($this->shouldCompact()) {
            $this->compact($this->history);
        }
    }

    protected function shouldCompact(): bool
    {
        return $this->threshold() < count($this->history);
    }

    /**
     * Read the threshold from the agent's CompactsAfter attribute,
     * falling back to the default.
     */
    protected function threshold(): int
    {
        $attributes = (new ReflectionClass($this))->getAttributes(CompactsAfter::class);

        $config = $attributes
            ? $attributes[0]->newInstance()
            : new CompactsAfter($this->defaultThreshold);

        return $config->threshold;
    }

    /**
     * Summarize the conversation so far and reset the history to that summary.
     */
    protected function compact(array $history): void
    {
        $response = Http::timeout(180)
            ->withToken(config('services.openai.key'))
            ->post('https://api.openai.com/v1/responses', [
                'model' => config('services.openai.model'),
                'instructions' => 'Summarize the following conversation history concisely. Preserve key facts, identifiers such as ad account ids, decisions, tool results, and unresolved questions.',
                'input' => $history,
            ])
            ->throw()
            ->json();

        $this->history = [[
            'role' => 'user',
            'content' => 'Earlier conversation summary: '.$this->textFrom($response),
        ]];
    }

    protected function runTool(array $call): void
    {
        $this->toolCalls[] = $call['name'];

        foreach ($this->tools() as $tool) {
            if ($tool->definition()['name'] === $call['name']) {
                $this->appendToolOutput($call, (string) $tool->use(json_decode($call['arguments'], true) ?? []));

                return;
            }
        }

        // Every function_call must get an output or the next request is rejected.
        $this->appendToolOutput($call, "Error: no tool named {$call['name']} is available.");
    }

    protected function appendToolOutput(array $call, string $output): void
    {
        $this->history[] = [
            'type' => 'function_call_output',
            'call_id' => $call['call_id'],
            'output' => $output,
        ];
    }

    protected function runModel(): array
    {
        $payload = [
            'model' => config('services.openai.model'),
            'instructions' => $this->instructions(),
            'input' => $this->history,
            'tools' => array_map(fn (Tool $tool) => $tool->definition(), $this->tools()),
        ];

        // Only declare a format when the agent actually wants one.
        if ($schema = $this->schema()) {
            $payload['text'] = [
                'format' => [
                    'type' => 'json_schema',
                    'name' => 'response',
                    'strict' => true,
                    'schema' => $schema,
                ],
            ];
        }

        return Http::timeout(300)
            ->withToken(config('services.openai.key'))
            ->post('https://api.openai.com/v1/responses', $payload)
            ->throw()
            ->json();
    }
}
