<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

require __DIR__ . '/vendor/autoload.php';
use OpenAI;
$openaiKey = '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';
$client = OpenAI::client($openaiKey);
$threadId = $_GET['threadid'];
$maxRetries = 10;
$attempts = 0;
$assistantMessage = null;

while ($attempts < $maxRetries) {
    // Step 4: Fetch the latest messages from the thread
    $responseMessages = $client->threads()->messages()->list($threadId, [
        'limit' => 1, // We only want the most recent message
    ]);

    // Step 5: Extract the assistant's message
    foreach ($responseMessages['data'] as $message) {
        if ($message['role'] === 'assistant') {
            $assistantMessage = $message['content'];
            break 2; // Exit both loops once we find the assistant's response
        }
    }

    // Step 6: If no assistant response, wait before retrying
    if ($assistantMessage === null) {
        sleep(3); // Wait for 3 seconds before retrying (adjust if needed)
    }

    $attempts++;
}
//echo '<div class="col-sm-8">';
// Step 7: Display the assistant's response

if ($assistantMessage) {

    $gptResultRaw = $assistantMessage[0]['text']['value'];
    echo $gptResultRaw;
    //$gptResultRaw = json_decode($gptResultRaw);
    
    //$gptResult = array();
    
} else {
   echo "OpenAI Timeout";
}