<?php
declare(strict_types=1);
if(PHP_SAPI!=='cli')exit(1);
foreach(['config','logger','storage','history','bitrix','bitrix_bot','prompts','openai','crm','bot','bot_inbox']as$m)require_once __DIR__.'/../src/'.$m.'.php';
$worker=fopen(dirname((string)config('STATE_FILE')).'/bot_inbox_worker.lock','c');
if(!$worker||!flock($worker,LOCK_EX|LOCK_NB))exit(0);
$result=['started_at'=>date('c'),'checked'=>0,'processed'=>0,'errors'=>0];$start=time();
try{
 foreach(glob(botInboxDirectory().'/*.json')?:[]as$path){
  if(time()-$start>50)break;
  try{$r=readJsonFile($path);if(($r['status']??'')==='done')continue;$result['checked']++;$done=processBotInboxEvent($path);if(!($done['ok']??false))$result['errors']++;elseif(empty($done['skipped']))$result['processed']++;}
  catch(Throwable $e){$result['errors']++;logMessage('error','Inbox record failed; continuing',['file'=>basename($path),'error'=>$e->getMessage()]);}
 }
 $result['finished_at']=date('c');writeJsonFile(dirname((string)config('STATE_FILE')).'/bot_inbox_health.json',$result);echo json_encode($result).PHP_EOL;
}finally{flock($worker,LOCK_UN);fclose($worker);}
