<?php
// Hale-only bridge. The RCON secret lives outside the public document root.
ini_set('display_errors','0');
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');header('X-Content-Type-Options: nosniff');header('Referrer-Policy: no-referrer');
function reply($code,$data){http_response_code($code);echo json_encode($data);exit;}
if(($_SERVER['REQUEST_METHOD']??'')!=='POST')reply(405,['error'=>'POST required']);
if(isset($_SERVER['HTTP_ORIGIN'])&&$_SERVER['HTTP_ORIGIN']!=='https://trade.santasrv.com')reply(403,['error'=>'origin']);
if(strtolower(trim(explode(';',$_SERVER['CONTENT_TYPE']??'')[0]))!=='application/json')reply(415,['error'=>'JSON required']);
$raw=file_get_contents('php://input',false,null,0,513);if(strlen($raw)>512)reply(413,['error'=>'too large']);
$b=json_decode($raw,true);
if(!is_array($b)||!is_string($b['token']??null)||!preg_match('/\A[0-9a-f]{32}\z/D',$b['token']))reply(400,['error'=>'invalid token']);
$action=$b['action']??null;if(!in_array($action,['state','command','preview'],true))reply(400,['error'=>'invalid action']);
$allowed=$action==='state'?['token','action']:($action==='command'?['token','action','revision','key']:['token','action','webgl','status']);
if(array_diff(array_keys($b),$allowed))reply(400,['error'=>'unexpected fields']);
if($action==='command'){
 if(!is_int($b['revision']??null)||$b['revision']<1||$b['revision']>100000)reply(400,['error'=>'invalid revision']);
 if(!is_string($b['key']??null)||!preg_match('/\A(?:upgrade:1|hud:[01]|(?:buypassive|passiveon|passiveoff):(?:[0-9]|10)|stat:[a-z][a-z0-9_]{0,62}|(?:learn|skill|buyarmor|buyconsumable|buypet|buyweapon|armor|pet|weapon|use|droparmor|dropconsumable|droppet|dropweapon):[0-9]{1,4})\z/D',$b['key']))reply(400,['error'=>'invalid command']);
}
if($action==='preview')reply(200,['ok'=>true]); // Optional diagnostics, no gameplay writes.
function readexact($s,$n){$out='';while(strlen($out)<$n){$v=fread($s,$n-strlen($out));if($v===false||$v==='')throw new Exception('read');$out.=$v;}return $out;}
function packet($s){$n=unpack('V',readexact($s,4))[1];if($n<10||$n>65536)throw new Exception('packet');$p=readexact($s,$n);return [unpack('V',substr($p,0,4))[1],substr($p,8,-2),unpack('V',substr($p,4,4))[1]];}
function sendpacket($s,$id,$type,$body){$p=pack('VV',$id,$type).$body."\0\0";$p=pack('V',strlen($p)).$p;$offset=0;while($offset<strlen($p)){$n=fwrite($s,substr($p,$offset));if(!$n)throw new Exception('write');$offset+=$n;}}
try{
 $config=json_decode(file_get_contents(dirname(__DIR__,2).'/.hale-rpg-private/bridge.json'),true);
 if(!is_array($config)||!isset($config['password']))throw new Exception('config');
 // A fixed global concurrency lock bounds remote RCON connections. No token-named files.
 $lock=fopen(dirname(__DIR__,2).'/.hale-rpg-private/bridge.lock','c');
 if(!$lock||!flock($lock,LOCK_EX|LOCK_NB))reply(429,['error'=>'busy']);
 $s=stream_socket_client('tcp://node1.santasrv.com:27100',$errno,$error,3);
 if(!$s)throw new Exception('connect');stream_set_timeout($s,3);
 sendpacket($s,1,3,$config['password']);unset($config);
 do{$p=packet($s);if($p[0]===4294967295)throw new Exception('auth');}while($p[0]!==1||$p[2]!==2);
 $command='sm_rpgweb_remote '.($action==='state'?'state':'command').' '.$b['token'];
 if($action==='command')$command.=' '.$b['revision'].' '.$b['key'];
 sendpacket($s,2,2,$command);sendpacket($s,3,2,'echo RPGWEB_END');
 $out='';while(true){$p=packet($s);if($p[0]===3&&strpos($p[1],'RPGWEB_END')!==false)break;if($p[0]===2)$out.=$p[1];if(strlen($out)>600000)throw new Exception('size');}
 fclose($s);flock($lock,LOCK_UN);fclose($lock);
 if(strpos($out,'RPGWEB_EXPIRED')!==false)reply(410,['error'=>'session expired; reopen !rpg']);
 if($action==='command'){
  if(strpos($out,'RPGWEB_ACCEPTED')!==false)reply(202,['pending'=>true]);
  if(strpos($out,'RPGWEB_STALE')!==false)reply(409,['error'=>'stale revision']);
  reply(429,['error'=>'busy']);
 }
 preg_match_all('/RPGSTATEHEX ([0-9a-f]+)/',$out,$states);preg_match_all('/RPGAPPEARHEX ([0-9a-f]+)/',$out,$appear);
 $state=json_decode(hex2bin(implode('',$states[1])),true);
 if(!is_array($state)||($state['expires']??0)<=time())reply(503,['error'=>'Hale state unavailable']);
 $state['appearance']=json_decode(hex2bin(implode('',$appear[1])),true);reply(200,$state);
}catch(Throwable $e){reply(503,['error'=>'Hale bridge unavailable']);}
