<?php
namespace Nibiru\Module\Ai\Plugins\Tools;

use Nibiru\Module\Ai\Plugins\Tool;

/**
 * GET an HTTP URL and return its body. Useful for an agent that needs to
 * pull external knowledge (status pages, OpenAPI specs, an internal API).
 *
 * Safety: hosts and ports can be restricted via [AI] http_allowed_hosts[]
 * in ai.ini. By default, ALL hosts are allowed — lock down for production.
 */
class HttpGet extends Tool
{
    public function name(): string { return 'http_get'; }

    public function description(): string
    {
        return 'Fetch an HTTP/HTTPS URL with a GET request. Returns the response body, '
             . 'truncated to 8 KB.';
    }

    public function schema(): array
    {
        return [
            'url' => [
                'type' => 'string',
                'description' => 'Full URL to GET, including https:// scheme.',
                'required' => true,
            ],
            'headers' => [
                'type' => 'object',
                'description' => 'Optional request headers, e.g. {"Authorization": "Bearer …"}.',
                'required' => false,
            ],
        ];
    }

    public function execute(array $args): mixed
    {
        $url = (string) ($args['url'] ?? '');
        if ($url === '' || !preg_match('#^https?://#i', $url)) {
            return 'ERROR: url must be http(s)://...';
        }
        $headers = [];
        foreach ((array) ($args['headers'] ?? []) as $k => $v) {
            $headers[] = "$k: $v";
        }
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS      => 3,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_USERAGENT      => 'Nibiru-Agent/1.0',
        ]);
        $body = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err  = curl_error($ch);
        curl_close($ch);
        if ($body === false) return "ERROR: $err";
        $body = (string) $body;
        if (strlen($body) > 8192) $body = substr($body, 0, 8192) . "\n…[truncated]";
        return "HTTP $code\n$body";
    }
}
