<?php

use boru\ai\Bootstrap;

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/example_helpers.php';

$parsedArgs = exampleParseArgs($argv);
if (exampleHasFlag($parsedArgs, 'help')) {
    examplePrintUsageAndExit(
        'examples/mcp_http_proxy.php',
        'Run an MCP example against a boru/mcp HTTP proxy endpoint. Replace the placeholder URL before use.',
        '[--provider=openai|gemini] [--model=MODEL]',
        0
    );
}
if(!exampleHasFlag($parsedArgs, "url")) {
    echo "Error: Missing required --url flag. Please provide the URL of the MCP HTTP proxy endpoint." . PHP_EOL;
    exit(1);
}
$mcpUrl = exampleFlag($parsedArgs, 'url');
if (!filter_var($mcpUrl, FILTER_VALIDATE_URL)) {
    echo "Error: Invalid URL provided for --url flag. Please provide a valid URL." . PHP_EOL;
    exit(1);
}
$internalPort = exampleFlag($parsedArgs, 'internal-port');
if ($internalPort !== null) {
    $internalPort = (string)$internalPort;
    if ($internalPort === '' || !ctype_digit($internalPort)) {
        echo "Error: Invalid value provided for --internal-port. Please provide a numeric TCP port." . PHP_EOL;
        exit(1);
    }
}


$config = require __DIR__ . '/config.php';
$config->mcp(array(
    'enabled' => true,
    'client' => array(
        'driver' => 'http_proxy',
        'timeout' => 10,
    ),
    'discovery' => array(
        'enabled' => true,
    ),
    'servers' => array(
        'placeholder_mcp' => array(
            'transport' => 'http',
            'url' => $mcpUrl,
            'headers' => $internalPort !== null ? array(
                'internal-port' => $internalPort,
            ) : array(),
            'auth' => array(
                'type' => 'none',
            ),
        ),
    ),
));

Bootstrap::registerDefaults($config);

$ai = exampleCreateAi($parsedArgs, 'openai', 'mcp_http_proxy_example');
$ai->tryAddDiscoveredMcpTools('placeholder_mcp', function ($error) {
    fwrite(STDERR, '[mcp discovery warning] ' . $error['message'] . PHP_EOL);
});
$ai->addMessage('Call an appropriate MCP tool and summarize the result briefly.');

echo 'Configured MCP server: ' . $mcpUrl . PHP_EOL;
if ($internalPort !== null) {
    echo 'Configured boru/mcp internal-port header: ' . $internalPort . PHP_EOL;
} else {
    echo 'No internal-port header configured. This is fine for generic MCP HTTP proxies, but boru/mcp proxy endpoints usually require --internal-port.' . PHP_EOL;
}

$response = $ai->run();
echo rtrim($response->text()) . PHP_EOL;
