<?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 = 3;
$attempts = 0;
$assistantMessage = null;
sleep(3);
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) {
        //var_dump($message['content']);
        //echo "<br>";
        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 || count($assistantMessage) == 0) {
        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'];
    $gptResultRaw = str_replace("```json", "", $gptResultRaw);
    $gptResultRaw = str_replace("```", "", $gptResultRaw);
    $gptResultRaw = trim($gptResultRaw);
    echo $gptResultRaw;
    //$gptResultRaw = json_decode($gptResultRaw);
    
    //$gptResult = array();
    
} else {
   echo "OpenAI Timeout";
}