<?php

use boru\ai\AI;

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

if (!class_exists(\boru\boruai\Models\Functions\FunctionBase::class)) {
    fwrite(STDERR, "This example requires the optional boru/boruai package for legacy tool compatibility.\n");
    fwrite(STDERR, "Install it with: composer require boru/boruai\n");
    exit(1);
}

require __DIR__ . '/LegacyWeatherTemperatureTool.php';

$parsedArgs = exampleParseArgs($argv);
if (exampleHasFlag($parsedArgs, 'help')) {
    examplePrintUsageAndExit(
        'examples/weatherbot_legacy_tool.php',
        'Run a weatherbot example using a legacy boruai-defined tool adapted through boru\\ai compatibility.',
        '[--provider=openai|gemini] [--model=MODEL]',
        0
    );
}

exampleBootstrap();

$legacyContextObject = (object) array(
    'source' => 'legacy boruai context',
    'label' => 'rich object passthrough',
    'id' => 123,
    'meta' => (object) array(
        'kind' => 'demo',
        'active' => true,
    ),
);

$ai = exampleCreateAi($parsedArgs, 'openai', 'weatherbot_legacy_tool_example')
    ->setToolContextValue('temp', 69)
    ->setToolContextValue('someobject', $legacyContextObject)
    ->addLegacyTool('LegacyWeatherTemperatureTool')
    ->addMessage('What\'s the weather in Atlanta right now in Fahrenheit? Also, please generate a random sentence about the weather that is returned. Thanks!');

list($outputBuffer, $completionStatus, $functionCalls) = attachStreamHandlersToAi($ai);
$response = $ai->run();

$responsePayload = json_decode($response->text(), true);

echo PHP_EOL;
echo '---' . PHP_EOL;
echo 'Buffered text length: ' . strlen($outputBuffer->buffer()) . PHP_EOL;
echo 'Turn completion status: ' . ($completionStatus->status() ? $completionStatus->status() : 'unknown') . PHP_EOL;
echo 'Observed tool calls: ' . count($functionCalls->calls()) . PHP_EOL;
if (is_array($responsePayload) && isset($responsePayload['context_object'])) {
    echo 'Context object returned by tool:' . PHP_EOL;
    echo json_encode($responsePayload['context_object'], JSON_PRETTY_PRINT) . PHP_EOL;
}
echo rtrim($response->text()) . PHP_EOL;
