import { PHP, loadPHPRuntime } from '@php-wasm/universal';
// The version-pinned, self-hosted loader remains an external ES module.
import * as loader from './runtime/php-loader.mjs';
let php;
async function initialize(){
 const runtime=await loadPHPRuntime(loader);
 php=new PHP(runtime);
 for(const name of ['OrderStore.php','scenarios.php']){
  const response=await fetch(new URL('source/'+name+'.txt',self.location.href));if(!response.ok)throw new Error('A required PHP source file is unavailable.');
  php.writeFile('/'+name,await response.text());
 }
 postMessage({type:'ready'});
}
self.onmessage=async event=>{
 const config=event.data;
 if(!php||!['stock','retry','rollback','delivery','query'].includes(config.scenario)||!['fixed','broken'].includes(config.mode))return;
 try{
  php.writeFile('/config.json',JSON.stringify(config));
  const response=await php.run({code:'<?php require "/scenarios.php"; $c=json_decode(file_get_contents("/config.json"),true,8,JSON_THROW_ON_ERROR); echo json_encode(runScenario($c["scenario"],$c["mode"]),JSON_THROW_ON_ERROR);'});
  if(response.exitCode!==0)throw new Error(response.errors||'The PHP experiment did not finish.');
  postMessage({type:'result',result:JSON.parse(response.text)});
 }catch(error){postMessage({type:'error',message:error.message});}
};
initialize().catch(error=>postMessage({type:'error',message:error.message}));
