<?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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';
$assistantId= 'asst_qgkS3bLzfkDjS8JH472tWv9x';
if(isset($_GET['message'])){
	if($_GET['message'] == ""){
        echo "No message";exit;
    }
    $message  = $_GET['message'];
    $client = OpenAI::client($openaiKey);
    
    if(isset($_GET['thread_id']) && $_GET['thread_id'] != ""){

        $threadId = $_GET['thread_id'];

        // Send a message to the assistant in the existing thread
        $message = $client->threads()->messages()->create($threadId, [
            'role' => 'user',
            'content' => $message
        ]);

        // Run the assistant to process the message
        $run = $client->threads()->runs()->create($threadId, [
            'assistant_id' => $assistantId
        ]);

        do {
            sleep(3); // Avoid excessive API calls
            $runStatus = $client->threads()->runs()->retrieve($threadId, $run['id']);
        } while ($runStatus['status'] !== 'completed');
       
    }else{

        
        $response = $client->threads()->createAndRun([
            'assistant_id' => $assistantId,
            'model' => 'gpt-3.5-turbo',
            'thread' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message,
                    ],
                ],
            ],
        ]); 
        $threadId = $response->threadId;
        do {
            sleep(3); // Avoid excessive API calls
            $runStatus = $client->threads()->runs()->retrieve($threadId, $response->id);
        } while ($runStatus['status'] !== 'completed');

        
    }
    
	//sleep(3);
    $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 || count($assistantMessage) == 0) {
            sleep(3); // Wait for 3 seconds before retrying (adjust if needed)
        }

        $attempts++;
    }
    // Step 7: Display the assistant's response
   	
    $merchant= "";
    $receipt="";
    $receipt_date="";;
    $amount="";

    $result = array();
   // var_dump($assistantMessage);exit;
    if ($assistantMessage) {
        $gptResultRaw = $assistantMessage[0]['text']['value'];
        $gptResultRaw = str_replace("```json", "", $gptResultRaw);
        $gptResultRaw = str_replace("```", "", $gptResultRaw);
        $gptResultRaw = trim($gptResultRaw);
        //var_dump($gptResultRaw);exit;
        $resObj = json_decode($gptResultRaw);

        $locationArray = array();
        if(isset($resObj->locations) && $resObj->locations != null){
            $locationArray = $resObj->locations;
        }
        $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $result['locations'] = $locationArray;
        echo json_encode($result);exit;



         //echo $gptResultRaw;
    } else {
       
       $readThread = file_get_contents("https://ai.fireworksmedia.com/receipt/read_retail.php?threadid=".$threadId);

       if($readThread == false || $readThread == "OpenAI Timeout"){
            echo "OpenAI Timeout: ".$threadId;exit;
       }else{
        $resObj = json_decode($readThread);
        $locationArray = array();
        if(isset($resObj->locations) && $resObj->locations != null){
            $locationArray = $resObj->locations;
        }
        $result['thread_id'] = $threadId;
        $result['message'] = $resObj->message;
        $result['locations'] = $locationArray;
        echo json_encode($result);exit;
       }
       
    }
}
