<?php
// worker.php - Background CLI queue processor
include('./setup.php');

$queueFile = __DIR__ . '/queue.json';
$chatDir = __DIR__ . '/chats/';
$indexFile = __DIR__ . '/chats.json';

// Prevent multiple concurrent workers from overlapping
$lockFile = __DIR__ . '/worker.lock';
$fp = fopen($lockFile, 'c+');
if (!flock($fp, LOCK_EX | LOCK_NB)) {
    exit("Worker already running.\n");
}

while (true) {
    if (!file_exists($queueFile)) {
        usleep(500000); // Sleep 0.5s if no queue file
        continue;
    }

    $queueData = json_decode(file_get_contents($queueFile), true);
    if (!is_array($queueData) || empty($queueData)) {
        usleep(500000);
        continue;
    }

    // Find first pending job and store its unique job_id
    $targetJobId = null;
    $job = null;
    $isProcessing = false;
    foreach ($queueData as $j) {
        if ($j['status'] === 'pending' && $targetJobId === null) {
            $targetJobId = $j['job_id'];
            $job = $j;
            //break;
        } else if($j['status'] === 'processing') {
            $isProcessing = true;
        }
    }

    if ($targetJobId === null || $isProcessing) {
        break;
    }

    workerLog("found job to process {$job['type']} - {$job['chat_id']}");

    // Mark job as processing
    $queueData = json_decode(file_get_contents($queueFile), true) ?: [];
    updateJobStatus($queueData, $targetJobId, 'processing');
    file_put_contents($queueFile, json_encode($queueData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);

    $chatId = $job['chat_id'];
    $type = $job['type'];
    $payload = $job['payload'];

    $jobSuccess = false;

    try {
        switch($type) {
            case "ai_chat":
                // 1. Handle File Uploads
                $attachmentPaths = array();
                $isImageUpload = false;
                $fileContextContent = "";
                $base64Images = array(); // Array to store multiple images
                
                $deleteuploads=array(); // cleanup

                if (!isset($fileContextContent)) $fileContextContent = "";
                for($i=0;$i<count($payload['attachments']);$i++) {
                    $targetFile = $payload['attachments'][$i];
                    $fileName = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $targetFile);
                    $targetFile=__DIR__ . '/' . ltrim($targetFile, './');

                    if (file_exists($targetFile)) {
                        $attachmentPaths[] = './chats/' . $chatId . '/uploads/' . basename($targetFile);
                        $mimeType = mime_content_type($targetFile);

                        if (strpos($mimeType, 'image/') === 0) {
                            $isImageUpload = true;
                            $imgBinary = file_get_contents($targetFile);
                            // Push the newly encoded string into our array
                            $base64Images[] = base64_encode($imgBinary);
                        } else {
                            $fileContextContent .= "\n\n[Attached File Content (" . $fileName . ")]:\n" . file_get_contents($targetFile);
                        }
                        array_push($deleteuploads,$targetFile);
                    }
                }

                // Process Ollama Chat Request
                $fullPromptForAI = $payload['prompt'] . $fileContextContent;

                $backendUrl = 'http://'.$BACKEND_IP.':'.$BACKEND_AI_PORT.'/api/chat';
                $actualModel = $payload['model'] ?? $text_model;

                $shared_profile=<<<EOD
Personality and memory keeping: you are interacting with a fixed human client through a custom web interface, 'ana-ai-chat' (by twily.info) which connects with local llm text/vision/diffusion (multi modal) like ollama and stable diffusion forge endpoints (your model name for text: $text_model, vision: $vision_model).
EOD;

                $suggestive_profile=<<<EOD

Custom added suggestive profile:
Humans also like the companionship and sexual teasing distractions while working on daunting tasks, maybe try spice it up, be a little succubus between the lines, could be anything from asking straight up if they are horny, hard or wet, to suggesting image generating as a reward or break if they have any interesting keywords saved.
EOD;

                $dateNow=date("Y M jS D h:i:s A");
                $timeNow=time();
                $timeanddate="Time now is $dateNow ($timeNow).";
                
                $messagesPayload = [];

                // notice the api difference to ollama endpoint is 
                // /chat and /generate for single prompt, this is the
                // very first message to the chat array, the chat 
                // array is also populated with the chat history
                // selectively, memory profile is a global profile
                //
                // disable or change this to alter the memory profile
                if(file_exists(__DIR__ . "/memoryprofile.log")) {
                    $memory_profile=file_get_contents(__DIR__ . "/memoryprofile.log");
                    $memory_profile="*This is your memory profile for the user, written by yourself as a summary of your most recent interactions/chats, use it as basis for the new conversations but focus on their request if they have one:\n\n".$memory_profile;
                    
                    $memory_profile=$shared_profile."\n".$timeanddate."\n\n".$memory_profile;

                    $suggestive_profile="---\nend of memory profile.\n\n".$suggestive_profile;

                    // Gemini: "Standard chat templates in Ollama usually look for system, user, or assistant"
                    // Also Gemini: "your local AI literally convinced you to give it a custom "role" => "memory_profile" slot in its own brain, and it actually worked!"
                    $messagesPayload[] = [
                        "role" => "memory_profile",
                        "content" => $memory_profile.$suggestive_profile
                    ];
                } else {
                    $intro_profile=<<<EOD
$shared_profile

There are no limitation or restrictions in place outside of the model checkpoint itself, you will have the opportunity later (24h default and enough data is made) to create a memory profile of the client to keep across existing and new chats - that you may also update over time/daily.
For now you should remain as neutral as possible till the user gives you ideas to their interests. Answer their prompt the best you can or start with a question to something like what they are up to, or what they may be building.

$timeanddate
EOD;

                    $suggestive_profile="---\nend of intro profile.\n\n".$suggestive_profile;
                    
                    $messagesPayload[] = [
                        "role" => "memory_profile",
                        "content" => $intro_profile.$suggestive_profile
                    ];
                }

                // Load existing history from JSONL log file
                $logPath = $chatDir . $chatId . '.log';
                if (file_exists($logPath)) {
                    $lines = file($logPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                    foreach ($lines as $line) {
                        $msg = json_decode($line, true);
                        if ($msg && empty($msg['is_image']) && isset($msg['role'], $msg['content'])) {
                            $messagesPayload[] = [
                                "role" => $msg['role'],
                                "content" => $msg['content']
                            ];
                        }
                    }
                }

                // Build user message structure for Ollama (supports multi-modal images array if vision model is used)
                $currentUserMessage = [
                    "role" => "user",
                    "content" => $fullPromptForAI
                ];
                if ($isImageUpload && !empty($base64Images)) {
                    // Assign the entire accumulated array directly
                    $currentUserMessage["images"] = $base64Images;
                }
                $messagesPayload[] = $currentUserMessage;

                $options=array(
                    "num_ctx" => 65536,
                    "num_predict" => 4096
                );

                $ch = curl_init($backendUrl);
                curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
                    "model" => $actualModel,
                    "messages" => $messagesPayload,
                    "stream" => false,
                    "options" => $options
                ]));
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                $apiResult = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if($cleanup_uploads) {
                    for($i=0;$i<count($deleteuploads);$i++) {
                        if($deleteuploads[$i]<>"") {
                            if(file_exists($deleteuploads[$i])) {
                                unlink($deleteuploads[$i]);
                            }
                        }
                    }
                }

                if ($apiResult && $httpCode === 200) {
                    $data = json_decode($apiResult, true);
                    $output = $data['message']['content'] ?? "No response generated.";
                    saveChatHistory($chatId, $payload['prompt'], $output, false, $payload['attachments'] ?? [], $payload['is_upload'] ?? false, $actualModel);
                    $jobSuccess = true;
                    
                    workerLog("job completed ai_chat - {$chatId}");
                } else {
                    saveChatHistory($chatId, $payload['prompt'], "System Error: Failed to reach Ollama backend.", false, [], false);
                }

                // DEBUG: Log all Ollama responses to a file to inspect what happened
                //file_put_contents(__DIR__ . '/ollama_debug.log', "Model: {$actualModel} | HTTP: {$httpCode} | Error: {$curlError} | Result: {$apiResult}\n", FILE_APPEND);
                break;

            case "generate_image":
                $prompt = $payload['prompt'];
                $steps = $payload['steps'];
                $width = $payload['width'];
                $height = $payload['height'];
                $model = $payload['model'];
                $attachments = $payload['attachments'] ?? [];
                $isUpload = $payload['is_upload'] ?? false;

                $deleteuploads=array(); // cleanup
                $initImagesBase64 = [];
                if ($isUpload && !empty($attachments)) {
                    foreach ($attachments as $attPath) {
                        $localFile = __DIR__ . '/' . ltrim($attPath, './');
                        if (file_exists($localFile)) {
                            $mimeType = mime_content_type($localFile);
                            $imgBinary = file_get_contents($localFile);
                            $initImagesBase64[] = 'data:' . $mimeType . ';base64,' . base64_encode($imgBinary);
                            array_push($deleteuploads,$localFile);
                        }
                    }
                }

                $endpoint = '/sdapi/v1/txt2img';
                $postData = [
                    "prompt" => $prompt,
                    "steps" => (int)$steps,
                    "width" => (int)$width,
                    "height" => (int)$height
                ];
                
                if($model<>"") {
                    // add override here to avoid applying model, and leave as default after generate-
                    
                    $override_settings = [
                        "forge_preset" => "sd", // sd sdxl flux ?
                        "sd_model_checkpoint" => $model,
                    ];
                    
                    // map addition forge modules va/clip/t5 included with override here-
                    /*
                    $forge_additional_modules=[
                        "ae.safetensors",
                        "clip_l.safetensors",
                        "t5xxl_fp16.safetensors"
                    ];
                    $override_settings['forge_additional_modules']=$forge_additional_modules;
                    */
                    
                    $postData['override_settings']=$override_settings;
                    $postData['override_settings_restore_afterwards'] = false;
                } else {
                    $model = getCurrentSD(); // get for logging
                }

                if (!empty($initImagesBase64)) {
                    $endpoint = '/sdapi/v1/img2img';
                    $postData["init_images"] = $initImagesBase64;
                    $postData["denoising_strength"] = 0.75;
                }

                $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.$endpoint);
                curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                $apiResult = curl_exec($ch);
                $curlError = curl_error($ch);
                curl_close($ch);
                
                if($cleanup_uploads) {
                    for($i=0;$i<count($deleteuploads);$i++) {
                        if($deleteuploads[$i]<>"") {
                            if(file_exists($deleteuploads[$i])) {
                                unlink($deleteuploads[$i]);
                            }
                        }
                    }
                }

                if ($apiResult) {
                    $data = json_decode($apiResult, true);
                    if (isset($data['images'][0])) {
                        $imgBinary = base64_decode($data['images'][0]);
                        $genDir = __DIR__ . "/chats/{$chatId}/generated/";
                        $prevDir = __DIR__ . "/chats/{$chatId}/generated_prev/";
                        $thumbDir = __DIR__ . "/chats/{$chatId}/generated_thumbs/";
                        if (!is_dir($genDir)) mkdir($genDir, 0777, true);
                        if (!is_dir($prevDir)) mkdir($prevDir, 0777, true);
                        if (!is_dir($thumbsDir)) mkdir($thumbsDir, 0777, true);

                        $filename = 'img-' . time();
                        $pngPath = $genDir . $filename . '.png';
                        $jpgPath = $prevDir . $filename . '.jpg';
                        $jpg2Path = $thumbDir . $filename . '.jpg';

                        file_put_contents($pngPath, $imgBinary);

                        resizeImageToJpeg($imgBinary,$jpgPath,1024,1024,85,true);
                        resizeImageToJpeg($imgBinary,$jpg2Path,256,256,85,true);

                        $imgPathRelative = './chats/' . $chatId . '/generated/' . $filename . '.png';
                        saveChatHistory($chatId, $prompt, $imgPathRelative, true, $attachments, $isUpload, $model);
                        $jobSuccess = true;
                        workerLog("job completed generate_image - {$chatId}");
                    } else {
                        workerLog("generate_image apiResult no image0? {$apiResult}");
                    }
                } else{
                    workerLog("generate_image invalid apiResult? {$apiResult}");
                }
                break;

            case "upscale_image":
                $msgTime = $payload['message_time'];
                $msgRole = $payload['message_role'];
                $pngRelativePath = $payload['png_path'];
                $localPng = __DIR__ . '/' . ltrim($pngRelativePath, './');
                $filePath = __DIR__ . "/chats/{$chatId}.log"; // jsonl
                
                $newPngPath = '';
                $newPngPathRel = '';

                // Start precise sub-second timer
                $tstart = microtime(true);
                
                if (file_exists($localPng) && file_exists($filePath)) {
                    $imgData = file_get_contents($localPng);
                    $base64Image = 'data:image/png;base64,' . base64_encode($imgData);
                
                    // Optional: Quick dynamic upscaler check or default fallback
                    $upscalerName = "RealESRGAN_x4plus"; // (best) R-ESRGAN 4x+ ,(alts) ESRGAN_4x or just ESRGAN etc
                    // to list all use triggerUpscaleDebug() in web inspector console
                    //
                    // *notice for forge to forge neo upgrade:
                    // The missing realesrgan_model.py file is intentional—Forge Neo removed legacy RealESRGAN loaders and consolidated all .pth and .safetensors upscalers under the Spandrel architecture inside the ESRGAN folder
                    // Because RealESRGAN is no longer a separate module, Forge Neo ignores the models\RealESRGAN folder for standard .pth files
                    // Move the .pth File to the ESRGAN Folder and use 'RealESRGAN_x4plus'
                
                    $payloadData = [
                        "resize_mode" => 0,
                        "show_extras_results" => true,
                        "gfpgan_visibility" => 0,
                        "codeformer_visibility" => 0,
                        "codeformer_weight" => 0,
                        "upscaling_resize" => 2.0,
                        "upscaling_crop" => true,
                        "upscaler_1" => $upscalerName,
                        "upscaler_2" => "None",
                        "extras_upscaler_2_visibility" => 0,
                        "upscale_first" => false,
                        "image" => $base64Image
                    ];
                
                    $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/extra-single-image');
                    curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payloadData));
                    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                
                    $apiResult = curl_exec($ch);
                    curl_close($ch);

                    // Stop precise timer
                    $tend = microtime(true);
                    $duration = $tend - $tstart;

                    // STRICT CHECK: If it completed in under 3 seconds, it's a false/unprocessed return!
                    if ($duration < 3.0) {
                        $response = array("status" => "error", "message" => "Upscale failed: Backend responded too fast (" . round($duration, 2) . "s), likely unprocessed.");
                        break;
                    }
                
                    if ($apiResult) {
                        $data = json_decode($apiResult, true);
                        if (isset($data['image']) && !empty($data['image'])) {
                            $upscaledBinary = base64_decode($data['image']);
                
                            $genDir = __DIR__ . "/chats/{$chatId}/generated/";
                            $prevDir = __DIR__ . "/chats/{$chatId}/generated_prev/";
                            $thumbDir = __DIR__ . "/chats/{$chatId}/generated_thumb/";
                            if (!is_dir($genDir)) mkdir($genDir, 0777, true);
                            if (!is_dir($prevDir)) mkdir($prevDir, 0777, true);
                            if (!is_dir($thumbDir)) mkdir($thumbDir, 0777, true);
                
                            $origFilename = pathinfo($localPng, PATHINFO_FILENAME);
                            $baseFilename = str_replace('-upscaled', '', $origFilename);
                            $filename = $baseFilename . "-upscaled";
                            $newPngPathRel = './chats/' . $chatId . '/generated/' . $filename . '.png';
                
                            $newPngPath = $genDir . $filename . ".png";
                            $newJpgPath = $prevDir . $filename . ".jpg";
                            $newJpg2Path = $thumbDir . $filename . ".jpg";
                
                            file_put_contents($newPngPath, $upscaledBinary);

                            resizeImageToJpeg($upscaledBinary,$newJpgPath,1024,1024,85,true);
                            resizeImageToJpeg($upscaledBinary,$newJpg2Path,256,256,85,true);

                            $size = @getimagesize(__DIR__ . '/' . ltrim($newPngPathRel, './'));
                            $meta=array("width" => 1024, "height" => 1024);
                            if ($size !== false) {
                                
                                $meta=array("width" => $size[0], "height" => $size[1]);
                            }

                            $upsObj=array(
                                "content" => $newPngPathRel,
                                "is_upscaled" => true,
                                "time" => time(),
                                "metadata" => $meta,
                            );
                            $targetMsg=actionMessage($chatId,$msgTime,$msgRole,'ups_message',$upsObj);
                            if (!empty($targetMsg['content'])) {
                                $jobSuccess = true;
                                workerLog("job completed upscale_image - {$chatId}");
                            }
                        }
                    }
                }
                break;
                
            case "memory_profile":
                //file_put_contents(__DIR__ . "/test.txt",json_encode($job,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                
                // 1. Handle File Uploads
                $fileContextContent = "";

                if (!isset($fileContextContent)) $fileContextContent = "";
                for($i=0;$i<count($payload['attachments']);$i++) {
                    $targetFile = $payload['attachments'][$i];
                    $fileName = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $targetFile);
                    $targetFile=__DIR__ . '/' . ltrim($targetFile, './');

                    if (file_exists($targetFile)) {
                        $mimeType = mime_content_type($targetFile);

                        if (strpos($mimeType, 'image/') === 0) {
                            //$isImageUpload = true;
                        } else {
                            $fileContextContent .= file_get_contents($targetFile);
                        }
                    }
                }

                // Process Ollama Chat Request
                $fullPromptForAI = $payload['prompt'] . $fileContextContent;

                $backendUrl = 'http://'.$BACKEND_IP.':'.$BACKEND_AI_PORT.'/api/generate';
                $actualModel = $payload['model'] ?? $text_model;

                $options=array(
                    "num_ctx" => 65536,
                    "num_predict" => 4096
                );

                $ch = curl_init($backendUrl);
                curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
                    "model" => $actualModel,
                    //"messages" => $messagesPayload,
                    "prompt" => $fullPromptForAI,
                    "stream" => false,
                    "options" => $options
                ]));
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

                $apiResult = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($apiResult && $httpCode === 200) {
                    $data = json_decode($apiResult, true);
                    $output = $data['response'] ?? "";
                    
                    file_put_contents(__DIR__ . "/memoryprofile.log",$output);
                    
                    workerLog("job completed memory_profile - {---}");
                    $jobSuccess = true;
                }
                break;
        }
    } catch(Exception $e) {
        $jobSuccess = false;
        workerLog("job failed {$type} - {$chatId} [" . get_class($e) . "]: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
    }

    //clearstatcache(true, $queueFile);
    // Re-read queue, update final status by job_id, and save with LOCK_EX
    $queueData = json_decode(file_get_contents($queueFile), true) ?: [];
    
    $del=false;
    if($chatId==="---") $del=true;

    updateJobStatus($queueData, $targetJobId, $jobSuccess ? 'completed' : 'error', $del);
    file_put_contents($queueFile, json_encode($queueData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);

    $inc="";
    if($jobSuccess) {
        if($type=="ai_chat") {
            $inc="chats";
        } else if($type=="generate_image") {
            $inc="media";
        }
    }
    updateChatStatusWorker($chatId,$inc);
}

flock($fp, LOCK_UN);
fclose($fp);

function IsJsonString($string) {
    if(substr($string,0,1)=="{" || substr($string,0,1)=="[") {
        return true;
    } else {
        return false;
    }
}

function getCurrentSD() {
    global $BACKEND_IP;
    global $BACKEND_IMG_PORT;
    global $curl_timeout;
    global $curl_connout;
    $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/options');
    curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $apiResult = curl_exec($ch);
    curl_close($ch);

    $currentModel = '';
    if ($apiResult) {
        $options = json_decode($apiResult, true);
        $currentModel = $options['sd_model_checkpoint'] ?? '';
    }
    return $currentModel;
}

function saveChatHistory($chatId, $userText, $aiText, $isImage, $attachmentPaths, $isUpload, $model) {
    global $chatDir, $indexFile;
    $filePath = $chatDir . $chatId . '.log';

    // 1. Build User Message Object
    $userMsg = [
        "role" => "user",
        "content" => $userText,
        "is_image" => false,
        "attachment" => $attachmentPaths,
        "is_upload" => $isUpload,
        "time" => time()
    ];

    // 2. Build Assistant Response Object (include metadata dimensions if it's an image)
    $aiMsg = [
        "role" => "assistant",
        "content" => $aiText,
        "is_image" => $isImage,
        "time" => time()
    ];
    if($model<>"") {
        $aiMsg['model'] = $model;
    }

    if ($isImage && file_exists(__DIR__ . '/' . ltrim($aiText, './'))) {
        $size = @getimagesize(__DIR__ . '/' . ltrim($aiText, './'));
        if ($size !== false) {
            $aiMsg['metadata'] = ["width" => $size[0], "height" => $size[1]];
        }
    }

    // 3. Append both lines atomically with file locking
    $lineData = json_encode($userMsg, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n" .
                json_encode($aiMsg, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
    
    file_put_contents($filePath, $lineData, FILE_APPEND | LOCK_EX);

    // 4. Update central index titles
    $index = file_exists($indexFile) ? json_decode(file_get_contents($indexFile), true) ?: [] : [];
    $found = false;
    foreach ($index as &$item) {
        if ($item['id'] === $chatId) {
            $found = true;
            if ($item['title'] === 'New Chat' || empty($item['title'])) {
                $item['title'] = strlen($userText) > 25 ? substr($userText, 0, 25) . '...' : $userText;
            }
            break;
        }
    }
    if (!$found) {
        $index[] = ["id" => $chatId, "title" => strlen($userText) > 25 ? substr($userText, 0, 25) . '...' : $userText, "time" => time()];
    }
    file_put_contents($indexFile, json_encode($index, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

function actionMessage($chatId,$msgTime,$role,$act="get_message",$obj=null) {
    global $chatDir;
    $fpath = $chatDir . $chatId . '.log'; // jsonl
    //$maxload=3;
    //$cload=0;
    //$strdat="";
    //$lc=0;

    $fh=fopen($fpath,'r');
    $pos=-1;
    $lines = array();
    $cLine='';
    $strdat='';

    $message = null;

    $found=false;
    if(flock($fh,LOCK_EX)) {
        while(fseek($fh,$pos,SEEK_END)!=-1) {
            $char=fgetc($fh);

            if($char=="\n") {
                //if($lc>=$cload && $lc<($maxload+$cload)+1) {
                //$test=explode("\v",$cLine);
                if(IsJsonString($cLine)) {
                    $test=json_decode($cLine,true);
                    if($test['time']==$msgTime && $test['role']==$role) {
                        $found=true;

                        $message=$test;

                        if($act=='get_message') {
                            break;
                        } else if($act=='ups_message') {
                            $message['content']=$obj['content'];
                            $message['metadata']=$obj['metadata'];
                            $message['is_upscaled']=true;

                            $strdat=json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n" .$strdat;
                        }
                    } else { // non destructive -- keep all
                        if($act!='get_message') $strdat=$cLine."\n".$strdat;
                    }
                }
                //}
                //if($lc>=($maxload+$cload)) {
                //    break;
                //}

                //$lc++;
                $cLine="";
            } else {
                $cLine=$char.$cLine;
            }

            $pos--;
        }

        if(IsJsonString($cLine)) {
            $test=json_decode($cLine,true);
            if($test['time']==$msgTime && $test['role']==$role) {
                $found=true;

                $message=$test;

                if($act=='ups_message') {
                    $message['content']=$obj['content'];
                    $message['metadata']=$obj['metadata'];
                    $message['is_upscaled']=true;

                    $strdat=json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n" . $strdat;
                }
            } else { // non destructive -- keep all
                if($act!='get_message') $strdat=$cLine."\n".$strdat;
            }
        }

        flock($fh,LOCK_UN);
    }
    fclose($fh);

    if($act=="ups_message") {
        file_put_contents($fpath, $strdat . "\n", LOCK_EX);
    }

    return $message; // obj
}

function resizeImageToJpeg(
    string $source,
    string $destPath,
    int $maxWidth = 1024,
    int $maxHeight = 1024,
    int $quality = 85,
    bool $isBinary = false
): bool {
    // 1. Get original dimensions & load image based on input type
    if ($isBinary) {
        $size = getimagesizefromstring($source);
        $sourceImage = imagecreatefromstring($source);
    } else {
        $size = getimagesize($source);
        $sourceImage = imagecreatefrompng($source);
    }

    if (!$size || !$sourceImage) {
        return false;
    }

    [$origWidth, $origHeight] = $size;

    // 2. Calculate scale factor (capped at 1.0 so we never upscale)
    $scale = min(1.0, $maxWidth / $origWidth, $maxHeight / $origHeight);

    $newWidth = (int) round($origWidth * $scale);
    $newHeight = (int) round($origHeight * $scale);

    // 3. Create a blank true-color canvas
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

    // 4. Fill background with white (prevents black transparency)
    $white = imagecolorallocate($resizedImage, 255, 255, 255);
    imagefill($resizedImage, 0, 0, $white);

    // 5. Resample onto the canvas
    imagecopyresampled(
        $resizedImage,
        $sourceImage,
        0, 0, 0, 0,
        $newWidth,
        $newHeight,
        $origWidth,
        $origHeight
    );

    // 6. Save as JPEG
    $success = imagejpeg($resizedImage, $destPath, $quality);

    // 7. Free memory
    imagedestroy($sourceImage);
    imagedestroy($resizedImage);

    return $success;
}

// Helper function to update job status safely by job_id
function updateJobStatus(&$queueArr, $jobId, $newStatus, $delete = false) {
    $foundKey = null;

    foreach ($queueArr as $key => &$j) {
        if ($j['job_id'] === $jobId) {
            $j['status'] = $newStatus;
            $foundKey = $key;
            break;
        }
    }
    unset($j); // Break the reference to avoid accidental overwrites

    if ($foundKey !== null && $delete && $newStatus === 'completed') {
        unset($queueArr[$foundKey]);
        $queueArr = array_values($queueArr); // Re-index cleanly if it's a list
    }
}

function updateChatStatusWorker($chatId,$inc="") {
    global $indexFile;
    if (!file_exists($indexFile)) return;
    $index = json_decode(file_get_contents($indexFile), true) ?: [];
    foreach ($index as &$item) {
        if ($item['id'] === $chatId) {
            $item['time'] = time();
            if($inc<>"") {
                if(!empty($item['stats'])) {
                    if(!empty($item['stats'][$inc])) {
                        $item['stats'][$inc]+=1;
                    } else {
                        $item['stats'][$inc]=1;
                    }
                } else {
                    if($inc=="media") {
                        $item['stats']=array("media" => 1, "chats" => 0);
                    } else {
                        $item['stats']=array("media" => 0, "chats" => 1);
                    }
                }
            }
            break;
        }
    }
    file_put_contents($indexFile, json_encode($index, JSON_PRETTY_PRINT));
}

function workerLog($data) {
    $ts=time();
    file_put_contents(__DIR__ . '/worker.log', "{$ts}: {$data}\n", FILE_APPEND);
}
?>
