<?php
    error_reporting(0);
    //error_reporting(E_ALL & ~E_NOTICE);
    date_default_timezone_set("Europe/Oslo");

    // since version 1.0.6 keeping track in chats.json for msg count
    // if missing or need to update the count for display in sidebar
    //
    // this will count all response messages in each chat and assign
    // to chats.json, messages past 1.0.6 will count automatic, 
    // including delete of messages. this can be used to re-sync-
    //
    // **if using rebuild-chat-json.php must use this after to sync!

    //$files=ListFilesInFolder("./chats");
    //$arr=[];
    //for($i=0;$i<count($files);$i++) {
    //    $ext=substr($files[$i],strrpos($files[$i],".")+1);
    //    if(strtolower($ext)=="log") {
    //        $arr[]=$files[$i];
    //    }
    //}
    //
    $data=file_get_contents("./chats.json");
    $arr=json_decode($data,true);

    $chats=[];
    for($i=0;$i<count($arr);$i++) {
        $chatId=$arr[$i]['id']; // id

        $chatfile="./chats/".$chatId.".log";
        //$lastmtime=filemtime($chatfile); // time

        $fdata=file_get_contents($chatfile);
        $flist=explode("\n",$fdata);
        //$title="New Chat"; // title
        //
        $imagine=0;
        $ai=0;
        for($j=0;$j<count($flist);$j++) {
            if(IsJsonString($flist[$j])) {
                $msg=json_decode($flist[$j],true);
                //if($msg['role']=="user") {
                //    $userText=$msg['content'];
                //    $title=strlen($userText) > 25 ? substr($userText, 0, 25) . '...' : $userText;
                //    break;
                //}
                if($msg['role']=="assistant") {
                    if(!empty($msg['is_image'])) {
                        $imagine++;
                    } else {
                        $ai++;
                    }
                }
            }
        }

        $arr[$i]['stats']=array("media" => $imagine, "chats" => $ai);

        //$obj=[
        //    "id" => $chatId,
        //    "title" => $title,
        //    "time" => $lastmtime
        //    //"status" => "idle"
        //];
    } 

    echo "found to update chats.json:<br><br>";
    // preview
    //echo json_encode($arr);
    echo '<pre>'.json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."</pre>";

    // write with backup
    $write=true;
    if($write) { 
        if(file_exists("./chats.json")) {
            $num=1;
            while(file_exists("./chats.json_copy".$num)) {
                $num++;
            }
            rename("./chats.json","./chats.json_copy".$num);
        }

        echo "writing data to chats.json...<br><br>";

        file_put_contents("./chats.json",json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);

        echo "done";
    }

    exit;

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

    function ListFoldersInFolder($dir="./chats") {
        $filesAndFolders = scandir($dir);
        $folders = [];

        foreach ($filesAndFolders as $item) {
            // Exclude relative pointers and check if it's a directory
            if ($item !== '.' && $item !== '..' && is_dir($dir . '/' . $item)) {
                $folders[] = $item;
            }
        }

        return $folders;
    }

    function ListFilesInFolder($dir="./chats") {
        $filesAndFolders = scandir($dir);
        $files = [];

        foreach ($filesAndFolders as $item) {
            // Exclude relative pointers and check if it's a directory
            if ($item !== '.' && $item !== '..' && is_file($dir . '/' . $item)) {
                $files[] = $item;
            }
        }

        return $files;
    }
?>
