<?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_BSr8WJl5OOQEtKzizzq43n66';
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{

        $resFile = $_GET['file_url'];
        $client = OpenAI::client($openaiKey);
        $response = $client->files()->upload([
            'purpose' => 'fine-tune',
            'file' => fopen($resFile, 'r'),
        ]);
        $fileid = $response->id;
        $response = $client->threads()->createAndRun([
            'assistant_id' => $assistantId,
            'model' => 'gpt-3.5-turbo',
            'thread' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $message.",remember result in json format",
                        'attachments' => [
                            [
                                'file_id' => $fileid,
                                'tools' => [
                                    [
                                        'type' => 'file_search',
                                    ]
                                ]
                            ]
                        ]
                    ],
                ],
            ],
        ]); 
        $threadId = $response->threadId;
        try {
            do {
                sleep(3); // Avoid excessive API calls
                $runStatus = $client->threads()->runs()->retrieve($threadId, $response->id);
            } while ($runStatus['status'] !== 'completed');
        } catch (\Exception $e) {
            //error_log("Error retrieving run status: " . $e->getMessage());
        }    
                
    }
    
    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;
        $resObjList = json_decode($gptResultRaw);
        //var_dump($gptResultRaw);


        if($resObjList == false){
             $allResult = array();
                $allResult['thread_id'] = $threadId;
                $allResult['message'] = $gptResultRaw;
                $allResult['places'] = array(); 
                echo json_encode($allResult);exit;
        }
        $locationArray = array();
        $allResult = array();
        $allResult['thread_id'] = $threadId;
        $allResult['message'] = $resObjList->message;
        $allResult['places'] = $resObjList->places;
        /*foreach($resObjList->places as $resObj){
           
            $result['no'] = $resObj->no;
            $result['title'] = $resObj->title;
            $result['summary'] = $resObj->summary;
            $result['place_id'] = $resObj->place_id;
            $result['image_ref'] = $resObj->image_ref;
            $result['pro'] = $resObj->pro;
            $result['con'] = $resObj->con;
            $result['reviews'] = $resObj->reviews;
            $allResult['places'] = $result;
        }*/
        echo json_encode($allResult);exit;



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

           if($readThread == false || $readThread == "OpenAI Timeout"){
                echo "OpenAI Timeout: ".$threadId;exit;
           }else{
             $resObjList = json_decode($readThread);
            //var_dump($gptResultRaw);

            if(!$resObjList->message){
                var_dump($resObjList);exit;
            }
            $locationArray = array();
            $allResult = array();
            $allResult['thread_id'] = $threadId;
            $allResult['message'] = $resObjList->message;
            $allResult['places'] = $resObjList->places;
            echo json_encode($allResult);exit;
           }
        
    }
}
