<?php

use boru\ai\Bootstrap;
use boru\ai\Config\Config;
use boru\ai\Stream\Listener\OutputBufferListener;

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

$parsedArgs = exampleParseArgs($argv);
if (exampleHasFlag($parsedArgs, 'help')) {
    examplePrintUsageAndExit(
        'examples/replay_last_n_turns.php',
        'Demonstrate conversation replay using the last_n_turns strategy.',
        '[--provider=openai|gemini] [--model=MODEL] [--turns=N]',
        0
    );
}

/** @var Config $config */
$config = exampleBootstrap();
$provider = exampleResolveProvider($parsedArgs, 'gemini');
$model = exampleResolveModel($parsedArgs, $provider);
$turns = (int)exampleFlag($parsedArgs, 'turns', 2);
if ($turns <= 0) {
    fwrite(STDERR, "--turns must be a positive integer.\n");
    exit(1);
}

$config->provider($provider, array(
    'replay' => array(
        'enabled' => true,
        'strategy' => 'last_n_turns',
        'max_turns' => $turns,
    ),
));
Bootstrap::registerDefaults($config);

$reference = 'replay_last_n_turns_example_' . $provider;

$prompts = array(
    'My name is Daniel. Please just acknowledge this briefly.',
    'I live in Atlanta. Please just acknowledge this briefly.',
    'My favorite color is green. Please just acknowledge this briefly.',
    'Without guessing beyond what is in memory, tell me my name, city, and favorite color. Also mention that replay strategy is last_n_turns=' . $turns . '.',
);

$outputBuffer = new OutputBufferListener();
$outputBuffer->onDelta(function ($event, $delta) {
    //echo $delta;
});
$outputBuffer->onDone(function ($event, $text) {
    //echo PHP_EOL . '[text complete]' . PHP_EOL;
});

foreach ($prompts as $index => $prompt) {
    $ai = exampleCreateAi($parsedArgs, $provider, 'replay_last_n_turns_example')
        ->model($model)
        ->reference($reference)
        ->addMessage($prompt)
        ->addEventListener($outputBuffer);

    echo '--- Turn ' . ($index + 1) . ' ---' . PHP_EOL;
    echo 'User: ' . $prompt . PHP_EOL;
    $response = $ai->run();
    echo 'Final text:' . PHP_EOL;
    echo rtrim($response->text()) . PHP_EOL . PHP_EOL;
}
