<?php

use boru\ai\Bootstrap;

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

$parsedArgs = exampleParseArgs($argv);
if (exampleHasFlag($parsedArgs, 'help')) {
    examplePrintUsageAndExit(
        'examples/conversation_memory_tools.php',
        'Run a conversation example with built-in conversation memory tools enabled through config.',
        '[--provider=openai|gemini] [--model=MODEL]',
        0
    );
}

$config = require __DIR__ . '/config.php';
$config->runtime(array(
    'conversation_memory' => array(
        'tools' => array(
            'enabled' => true,
            'title' => true,
            'summary' => true,
            'append_note' => true,
            'replace_notes' => false,
        ),
    ),
));
$config->persistence(array(
    'enabled' => true,
    'auto_schema' => true,
    'tables' => array(
        'conversation_notes' => 'ai_conversation_notes',
    ),
));

Bootstrap::ensurePersistenceSchema($config);
Bootstrap::registerDefaults($config);

$ai = exampleCreateAi($parsedArgs, 'openai', 'conversation_memory_tools_example')
    ->addMessage(
        'The user is planning a weekend in Atlanta. Answer their request. '
        . 'If useful, keep conversation memory updated with a short title, a concise rolling summary, '
        . 'and a few durable notes about preferences, decisions, or constraints.'
    )
    ->addMessage(
        'I want a relaxed weekend in Atlanta with good coffee, a bookstore stop, and one nice dinner. '
        . 'Keep the budget moderate and avoid anything too crowded late at night.'
    );

$response = $ai->run();
$memory = $ai->conversationMemory();

echo 'Response:' . PHP_EOL;
echo rtrim($response->text()) . PHP_EOL . PHP_EOL;

echo 'Conversation Memory:' . PHP_EOL;
if (!$memory) {
    echo "No conversation memory was loaded.\n";
    exit(0);
}

echo 'Title: ' . ($memory->title() ? $memory->title() : '[none]') . PHP_EOL;
echo 'Summary: ' . ($memory->summary() ? $memory->summary() : '[none]') . PHP_EOL;
echo 'Notes:' . PHP_EOL;

$notes = $memory->notes();
if (empty($notes)) {
    echo "- [none]\n";
    exit(0);
}

foreach ($notes as $note) {
    $line = '- ';
    if ($note->kind()) {
        $line .= '[' . $note->kind() . '] ';
    }
    $line .= $note->text();
    if ($note->confidence() !== null) {
        $line .= ' (confidence=' . $note->confidence() . ')';
    }
    echo $line . PHP_EOL;
}
