<?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_tcp.php',
        'Run an MCP example against a direct TCP MCP server.',
        '[--provider=openai|gemini] [--model=MODEL] --host=HOST --port=PORT [--token=TOKEN]',
        0
    );
}

if (!exampleHasFlag($parsedArgs, 'host')) {
    echo "Error: Missing required --host flag. Please provide the MCP TCP host." . PHP_EOL;
    exit(1);
}
if (!exampleHasFlag($parsedArgs, 'port')) {
    echo "Error: Missing required --port flag. Please provide the MCP TCP port." . PHP_EOL;
    exit(1);
}

$host = trim((string)exampleFlag($parsedArgs, 'host'));
if ($host === '') {
    echo "Error: Invalid value provided for --host. Please provide a non-empty host." . PHP_EOL;
    exit(1);
}

$port = (string)exampleFlag($parsedArgs, 'port');
if ($port === '' || !ctype_digit($port)) {
    echo "Error: Invalid value provided for --port. Please provide a numeric TCP port." . PHP_EOL;
    exit(1);
}

$token = exampleFlag($parsedArgs, 'token');
if ($token !== null) {
    $token = trim((string)$token);
    if ($token === '') {
        $token = null;
    }
}

$config = require __DIR__ . '/config.php';
$config->mcp(array(
    'enabled' => true,
    'client' => array(
        'driver' => 'tcp',
    ),
    'discovery' => array(
        'enabled' => true,
    ),
    'servers' => array(
        'placeholder_mcp' => array(
            'transport' => 'tcp',
            'host' => $host,
            'port' => (int)$port,
            'auth' => $token !== null ? array(
                'type' => 'bearer',
                'token' => $token,
            ) : array(
                'type' => 'none',
            ),
        ),
    ),
));

Bootstrap::registerDefaults($config);

$ai = exampleCreateAi($parsedArgs, 'openai', 'mcp_tcp_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 TCP server: ' . $host . ':' . $port . PHP_EOL;
if ($token !== null) {
    echo 'Configured MCP auth token: present' . PHP_EOL;
}

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