<?php
declare(strict_types=1);require __DIR__.'/lib.php';header('Content-Type: application/json; charset=utf-8');header('Cache-Control: no-store');
function body(): array {$r=file_get_contents('php://input');$x=$r?json_decode($r,true):[];return is_array($x)?$x:[];}
function out($x,int $c=200): void {http_response_code($c);echo json_encode($x,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);exit;}
try{$rid=reader_id();$a=$_GET['action']??'';$d=body();
if($a==='bootstrap')out(['config'=>public_config(),'reader'=>$rid]);
if($a==='find_path'){$x=find_path((string)($d['thought']??''));if(($x['status']??'')==='found')save_path($rid,$x['code']);out($x);}
if($a==='start')out(start_journey($rid,(string)($d['code']??'')));
if($a==='journey')out(journey((string)($_GET['id']??''))??['status'=>'error']);
if($a==='context')out(thread_context($rid,(string)($_GET['id']??'')));
if($a==='book')out(public_book($rid,(string)($_GET['id']??''),(string)($_GET['journey']??''))??['status'=>'error']);
if($a==='loose')out(public_loose((string)($_GET['id']??''))??['status'=>'error']);
if($a==='visit')out(visit($rid,(string)($d['journey']??''),(string)($d['kind']??''),(string)($d['id']??''),(int)($d['page']??1)));
if($a==='advance')out(advance_thread($rid,(string)($d['journey']??'')));
if($a==='retreat')out(retreat_thread($rid,(string)($d['journey']??'')));
if($a==='explore_check')out(explore_check($rid,(string)($d['journey']??'')));
if($a==='unlock'){grant($rid,(string)($d['book']??''));out(['status'=>'ok']);}
if($a==='explore')out(explore_book($rid,(string)($d['journey']??'')));
if($a==='return_thread')out(return_thread($rid,(string)($d['journey']??'')));
if($a==='map')out(map_data($rid,(string)($_GET['id']??'')));
if($a==='library')out(['books'=>library_data($rid)]);
if($a==='pulse')out(leave_pulse($rid,(string)($d['code']??''),(string)($d['text']??'')));
if($a==='pulses')out(['items'=>pulses_for((string)($_GET['code']??''))]);
out(['status'=>'error','message'=>'unknown action'],404);
}catch(Throwable $e){out(['status'=>'error','message'=>$e->getMessage()],500);} 
