<?php
declare(strict_types=1);
// Transport stub verifies request/response behavior without a key or network call.
foreach(['CURLOPT_POST','CURLOPT_HTTPHEADER','CURLOPT_POSTFIELDS','CURLOPT_CONNECTTIMEOUT','CURLOPT_TIMEOUT','CURLOPT_FOLLOWLOCATION','CURLOPT_PROTOCOLS','CURLOPT_WRITEFUNCTION','CURLPROTO_HTTPS','CURLINFO_HTTP_CODE'] as $i=>$name)if(!defined($name))define($name,$i+1);
function curl_init($url){$GLOBALS['ai_url']=$url;return new stdClass();}function curl_setopt_array($c,$options){$GLOBALS['ai_options']=$options;return true;}function curl_exec($c){$fn=$GLOBALS['ai_options'][CURLOPT_WRITEFUNCTION];$fn($c,json_encode(['choices'=>[['message'=>['content'=>'Test answer']]]]));return true;}function curl_getinfo($c,$key){return 200;}function curl_errno($c){return 0;}function curl_close($c){}
require_once __DIR__.'/../shared/lib/openrouter.php';
$messages=[['role'=>'system','content'=>assistant_prompt(false)],['role'=>'user','content'=>'Explain loops']];$answer=assistant_completion($messages,['key'=>'test-not-a-real-key','model'=>'test/model','site'=>'https://university.test']);$body=json_decode($GLOBALS['ai_options'][CURLOPT_POSTFIELDS],true);
if($answer!=='Test answer'||$GLOBALS['ai_url']!=='https://openrouter.ai/api/v1/chat/completions'||$body['messages']!==$messages||$body['model']!=='test/model'||$body['stream']!==false)throw new RuntimeException('Request shape mismatch');
if(!in_array('Authorization: Bearer test-not-a-real-key',$GLOBALS['ai_options'][CURLOPT_HTTPHEADER],true))throw new RuntimeException('Missing server authentication');
$history=assistant_history(array_merge([['role'=>'system','content'=>'untrusted']],array_fill(0,20,['role'=>'user','content'=>'hello'])));if(count($history)!==16)throw new RuntimeException('History bound');foreach($history as $entry)if($entry['role']==='system')throw new RuntimeException('Untrusted system role');
$rejected=false;try{assistant_completion([],['key'=>'','model'=>'test/model','site'=>'']);}catch(InvalidArgumentException){$rejected=true;}if(!$rejected)throw new RuntimeException('Empty key accepted');
echo "PASS: server-side OpenRouter endpoint, headers, bounded context, response parsing and missing-key handling without a live call.\n";
