<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/openrouter.php';start_auth_session();$public=($_GET['mode']??'private')==='public';$u=$public?null:require_auth();$key='assistant_'.($public?'public':(string)$u['id']);$action=$_GET['action']??'history';$settings=assistant_settings();
try{
 if(($_SERVER['REQUEST_METHOD']??'GET')==='GET'){reply(200,['messages'=>assistant_history($_SESSION[$key]['messages']??[]),'configured'=>$settings['key']!==''&&function_exists('curl_init'),'csrf_token'=>$_SESSION['csrf_token']]);}
 $data=post_data(10000);$state=$_SESSION[$key]??[];if(time()-(int)($state['busy']??0)<70)reply(409,['message'=>'Please wait for the current reply.']);
 if($action==='clear'){$_SESSION[$key]=['messages'=>[]];reply(200,['message'=>'New conversation started.']);}
 if($action!=='send')reply(405,['message'=>'Unsupported action.']);$message=text_field($data,'message',4000);if(!$message)throw new InvalidArgumentException('Type a message first.');if(!$settings['key'])throw new InvalidArgumentException('AI chat is not configured yet. Please contact the university administrator.');
 $subject=$public?(string)($_SERVER['REMOTE_ADDR']??'unknown'):(string)$u['id'];rate_limit($public?'assistant-public':'assistant-user',$subject,$public?20:60,3600);rate_limit('assistant-total','all',max(1,min(10000,(int)env_value('OPENROUTER_HOURLY_LIMIT','300'))),3600);
 $history=assistant_history($state['messages']??[]);$request=array_merge([['role'=>'system','content'=>assistant_prompt($public)]],array_map(static fn($m)=>['role'=>$m['role'],'content'=>$m['content']],$history),[['role'=>'user','content'=>$message]]);$sentAt=gmdate('Y-m-d\TH:i:s\Z');$_SESSION[$key]['busy']=time();session_write_close();
 try{$answer=assistant_completion($request,$settings);}catch(Throwable $e){start_auth_session();unset($_SESSION[$key]['busy']);throw $e;}
 start_auth_session();$_SESSION[$key]=['messages'=>assistant_history(array_merge(array_map(static fn($m)=>['role'=>$m['role'],'content'=>$m['content']],$history),[['role'=>'user','content'=>$message,'created_at'=>$sentAt],['role'=>'assistant','content'=>$answer,'created_at'=>gmdate('Y-m-d\TH:i:s\Z')]]))];reply(200,['message'=>$answer,'created_at'=>gmdate('Y-m-d\TH:i:s\Z')]);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('SLPS AI: '.get_class($e).' '.preg_replace('/[^a-zA-Z0-9_]/','_',substr($e->getMessage(),0,80)));reply(503,['message'=>'The AI service could not reply. Please try again later or contact university staff.']);}
