<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') { http_response_code(403); exit('Solo CLI'); }
require __DIR__.'/peer_sync_lib.php';
$interval=max(60,(int)($config['peer_interval_seconds']??120));
[$metaFile,$logFile]=peer_meta_paths($config);
if(empty($config['peer_sync_enabled'])){peer_log($logFile,'DAEMON no iniciado: réplica desactivada en config.php.');exit(0);}
peer_log($logFile,'DAEMON iniciado; intervalo '.$interval.' segundos.');
while(true){
  try{$r=peer_sync_once($config);peer_log($logFile,'OK '.json_encode($r,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));}
  catch(SiapaPeerException $e){peer_log($logFile,'ERROR '.$e->getMessage().' '.json_encode($e->details,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));}
  catch(Throwable $e){peer_log($logFile,'ERROR INTERNO '.$e->getMessage());}
  sleep($interval);
}
