<?php

use boru\ai\AI;

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

$parsedArgs = exampleParseArgs($argv);
if (exampleHasFlag($parsedArgs, 'help')) {
    examplePrintUsageAndExit(
        'examples/pdf_summary.php',
        'Summarize a PDF attachment with the selected provider.',
        '/path/to/file.pdf [--provider=openai|gemini] [--model=MODEL]',
        0
    );
}

if (!isset($parsedArgs['positionals'][0]) || !is_string($parsedArgs['positionals'][0]) || trim($parsedArgs['positionals'][0]) === '') {
    examplePrintUsageAndExit(
        'examples/pdf_summary.php',
        'Summarize a PDF attachment with the selected provider.',
        '/path/to/file.pdf [--provider=openai|gemini] [--model=MODEL]',
        1
    );
}

$pdfPath = $parsedArgs['positionals'][0];
if (!file_exists($pdfPath)) {
    fwrite(STDERR, 'PDF not found: ' . $pdfPath . PHP_EOL);
    exit(1);
}

exampleBootstrap();

$asset = AI::assetFromFile($pdfPath, 'file');

$ai = exampleCreateAi($parsedArgs, 'openai', 'pdf_summary_example')
    ->instructions('You are a precise document summarizer. Summarize attached PDFs clearly and concisely.')
    ->attachAsset($asset, 'user_data', 'file')
    ->addMessage('Please summarize the attached PDF. Include the main topic, key points, and any important conclusions.')
    ->onEvent(function ($event) {
        if ($event->type() === 'response.output_text.delta') {
            echo $event->delta();
        }
    });

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