<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';
class CodeRunnerException extends RuntimeException {}
function code_runner_config(): array {
 $base=rtrim(env_value('PISTON_API_URL','https://emkc.org/api/v2/piston'),'/');$url=parse_url($base);
 if(!$url||!in_array($url['scheme']??'',['https','http'],true)||empty($url['host'])||isset($url['user'])||isset($url['pass'])||isset($url['query'])||isset($url['fragment']))throw new CodeRunnerException('The configured runner URL is invalid.');
 if($url['scheme']==='http'&&env_value('PISTON_ALLOW_HTTP','0')!=='1')throw new CodeRunnerException('The runner requires HTTPS. Enable PISTON_ALLOW_HTTP only for a trusted private runner.');
 $header=env_value('PISTON_AUTH_HEADER','Authorization');$prefix=env_value('PISTON_AUTH_PREFIX','Bearer ');$token=env_value('PISTON_API_TOKEN');
 if(!preg_match('/^[A-Za-z0-9-]+$/',$header)||preg_match('/[\r\n]/',$prefix.$token))throw new CodeRunnerException('Runner authorization is not configured correctly.');
 return ['base'=>$base,'token'=>$token,'header'=>$header,'prefix'=>$prefix];
}
function code_runner_request(string $endpoint,?array $data=null): array {
 $config=code_runner_config();
 if(!in_array($endpoint,['runtimes','execute'],true))throw new CodeRunnerException('Invalid runner operation.');
 $headers=['Accept: application/json','Content-Type: application/json'];if($config['token']!=='')$headers[]=$config['header'].': '.$config['prefix'].$config['token'];
 if(function_exists('curl_init')){
 $curl=curl_init($config['base'].'/'.$endpoint);$body='';$tooLarge=false;
 curl_setopt_array($curl,[CURLOPT_RETURNTRANSFER=>false,CURLOPT_FOLLOWLOCATION=>false,CURLOPT_CONNECTTIMEOUT=>8,CURLOPT_TIMEOUT=>$endpoint==='execute'?30:15,CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2,CURLOPT_HTTPHEADER=>$headers,CURLOPT_WRITEFUNCTION=>static function($handle,string $chunk)use(&$body,&$tooLarge):int{if(strlen($body)+strlen($chunk)>1048576){$tooLarge=true;return 0;}$body.=$chunk;return strlen($chunk);}]);
 if($data!==null){curl_setopt($curl,CURLOPT_POST,true);curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data,JSON_THROW_ON_ERROR|JSON_UNESCAPED_SLASHES));}
 $ok=curl_exec($curl);$status=(int)curl_getinfo($curl,CURLINFO_HTTP_CODE);$error=curl_errno($curl);curl_close($curl);
 if($tooLarge)throw new CodeRunnerException('The runner response exceeded the allowed size. Reduce program output and try again.');
 if($ok===false)throw new CodeRunnerException($error===CURLE_OPERATION_TIMEDOUT?'The code runner timed out. Please try again.':'The code runner could not be reached. Please try again or ask the administrator to check its connection.');

 }else{
  if(!filter_var(ini_get('allow_url_fopen'),FILTER_VALIDATE_BOOLEAN))throw new CodeRunnerException('Enable PHP cURL or allow_url_fopen for the code runner.');
  $options=['http'=>['method'=>$data===null?'GET':'POST','header'=>implode("\r\n",$headers),'timeout'=>$endpoint==='execute'?30:15,'ignore_errors'=>true,'follow_location'=>0,'max_redirects'=>0],'ssl'=>['verify_peer'=>true,'verify_peer_name'=>true]];
  if($data!==null)$options['http']['content']=json_encode($data,JSON_THROW_ON_ERROR|JSON_UNESCAPED_SLASHES);
  $stream=@fopen($config['base'].'/'.$endpoint,'rb',false,stream_context_create($options));if(!$stream)throw new CodeRunnerException('The code runner could not be reached. Check its connection or enable PHP cURL.');
  $body=stream_get_contents($stream,1048577);$metadata=stream_get_meta_data($stream);fclose($stream);if(($metadata['timed_out']??false)||$body===false)throw new CodeRunnerException('The code runner timed out. Please try again.');if(strlen($body)>1048576)throw new CodeRunnerException('The runner response exceeded the allowed size. Reduce program output.');
  $status=0;foreach(($metadata['wrapper_data']??[]) as $line)if(preg_match('~^HTTP/\S+ ([0-9]{3})~',$line,$match))$status=(int)$match[1];
 }
 if(in_array($status,[401,403],true))throw new CodeRunnerException('Runner access is not authorized. The administrator must configure an authorized Piston endpoint or a self-hosted instance.');
 if($status===429)throw new CodeRunnerException('The runner is busy or its usage limit has been reached. Please wait and try again.');
 try{$result=json_decode($body,true,32,JSON_THROW_ON_ERROR);}catch(JsonException $e){throw new CodeRunnerException('The code runner returned an invalid response.');}
 if($status<200||$status>=300)throw new CodeRunnerException($status===400?'The runner rejected this program request. Check its language, version and file names.':'The code runner is temporarily unavailable. Please try again.');
 if(!is_array($result))throw new CodeRunnerException('The code runner returned an invalid response.');return $result;
}
function code_runner_runtimes(): array {
 $config=code_runner_config();$folder=private_storage_root().'/code-online';$key=hash('sha256',$config['base'].'|'.$config['header'].'|'.$config['prefix'].'|'.$config['token']);$file=$folder.'/runtimes-'.$key.'.json';$raw=null;
 if(is_file($file)&&filemtime($file)>time()-300){$raw=json_decode((string)file_get_contents($file),true);}
 if(!is_array($raw))$raw=code_runner_request('runtimes');
 $runtimes=[];$seen=[];
 foreach($raw as $item){if(!is_array($item)||!is_string($item['language']??null)||!is_string($item['version']??null))continue;$language=$item['language'];$version=$item['version'];if(strlen($language)>60||strlen($version)>60)continue;$pair=$language.'@'.$version;if(isset($seen[$pair]))continue;$seen[$pair]=true;$runtimes[]=['language'=>$language,'version'=>$version,'aliases'=>array_values(array_filter((array)($item['aliases']??[]),static fn($v)=>is_string($v)&&strlen($v)<80))];}
 if(!$runtimes)throw new CodeRunnerException('This runner has no language runtimes installed. Ask the administrator to install the required languages.');
 usort($runtimes,static fn($a,$b)=>strcasecmp($a['language'],$b['language'])?:version_compare($b['version'],$a['version']));
 if((is_dir($folder)||@mkdir($folder,0750,true))&&is_writable($folder)){$temporary=$file.'.'.bin2hex(random_bytes(6)).'.tmp';if(@file_put_contents($temporary,json_encode($runtimes),LOCK_EX)!==false)@rename($temporary,$file);}
 return $runtimes;
}
function code_runner_files(mixed $files): array {
 if(!is_array($files)||count($files)<1||count($files)>8)throw new InvalidArgumentException('Provide between 1 and 8 source files.');$out=[];$seen=[];$total=0;
 foreach($files as $file){if(!is_array($file)||!is_string($file['content']??null))throw new InvalidArgumentException('Each file needs text content.');$name=$file['name']??'main.txt';if(!is_string($name)||!preg_match('/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,79}$/',$name)||str_contains($name,'..'))throw new InvalidArgumentException('File names must be simple names without folders.');if(isset($seen[strtolower($name)]))throw new InvalidArgumentException('Source file names must be unique.');$seen[strtolower($name)]=true;$total+=strlen($file['content']);if($total>131072)throw new InvalidArgumentException('Source code must not exceed 128 KB in total.');$out[]=['name'=>$name,'content'=>$file['content'],'encoding'=>'utf8'];}
 if(trim(implode('',array_column($out,'content')))==='')throw new InvalidArgumentException('Write some code before running it.');return $out;
}
function code_runner_stage(mixed $raw): ?array {
 if(!is_array($raw))return null;$out=[];$truncated=false;
 foreach(['stdout','stderr','output','message'] as $key){$value=is_string($raw[$key]??null)?$raw[$key]:'';if(strlen($value)>131072){$value=substr($value,0,131072);$truncated=true;}$out[$key]=$value;}
 foreach(['code','signal','status','cpu_time','wall_time','memory'] as $key){$value=$raw[$key]??null;$out[$key]=(is_int($value)||is_float($value)||(is_string($value)&&strlen($value)<100))?$value:null;}
 $out['truncated']=$truncated;return $out;
}
