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

require __DIR__ . '/vendor/autoload.php';
use OpenAI;

putenv("GOOGLE_APPLICATION_CREDENTIALS=FireworksDigitalDevelopment-4b023518c824.json");
$openaiKey = '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';

if(isset($_GET['file_url'])){
	if($_GET['file_url'] == ""){
        echo "No file_url";exit;
    }
    $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' => 'asst_QrQ7JIOI2wDOAjKy554UerJ6',
	    'model' => 'gpt-4o-mini-2024-07-18',
	    'thread' => [
	        'messages' => [
	            [
	                'role' => 'user',
	                'content' => "return only the json result",
	                'attachments' => [
	                    [
	                        'file_id' => $fileid,
	                        'tools' => [
	                            [
	                                'type' => 'file_search',
	                            ]
	                        ]
	                    ]
	                ]
	            ],
	        ],
	    ],
	]);

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

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


    if ($assistantMessage) {

        $finalResult = $assistantMessage[0]['text']['value'];
        $finalResult = str_replace("```json","",$finalResult);
        $finalResult = str_replace("```","",$finalResult);
    
         echo $finalResult;
        //var_dump($gptResultRaw);
        /*$gptResultRaw = json_decode($gptResultRaw);
        $merchant= $gptResultRaw->merchant_name;
        $receipt=$gptResultRaw->receipt_no;
        $receipt_date=$gptResultRaw->receipt_date;
        $amount=$gptResultRaw->amount;
        echo $gptResultRaw;*/
        //$gptResult = array();
        
    } else {
        sleep(10);
       $readThread = file_get_contents("https://ai.fireworksmedia.com/receipt/read.php?threadid=".$threadId);
       if($readThread == false || $readThread == "OpenAI Timeout"){
            echo "OpenAI Timeout: ".$threadId;
       }else{
            $finalResult = str_replace("```json","",$readThread);
            $finalResult = str_replace("```","",$finalResult);

            echo $finalResult;
       }
       
    }

}


