const endpoints=new Set(['catalog.php','detail.php','quote.php','account.php','revision.php','upload.php','limited.php','legacy.php']);
export async function boundedFetch(input,init){
  const request=new Request(input,init);
  const url=new URL(request.url,location.href);
  const base=new URL('./api/',location.href);
  const file=url.pathname.slice(base.pathname.length);
  if(url.origin!==location.origin||!url.pathname.startsWith(base.pathname)||!endpoints.has(file)){
    throw new Error('Мастерская отправляет запросы только к восьми своим учебным PHP-маршрутам.');
  }
  return fetch(new Request(request,{credentials:'omit',redirect:'error'}));
}
export async function loadReference(target){
  const response=await fetch('./openapi.json',{credentials:'omit'});
  if(!response.ok)throw new Error('Не удалось загрузить OpenAPI');
  const spec=await response.json();
  spec.servers=[{url:new URL('./api',location.href).href,description:'Только учебный API этого же сайта'}];
  if(!window.Scalar){
    await new Promise((resolve,reject)=>{
      const s=document.createElement('script');s.src='./vendor/scalar.js';s.onload=resolve;s.onerror=()=>reject(new Error('Не удалось загрузить библиотеку Scalar'));document.head.append(s);
    });
  }
  return window.Scalar.createApiReference(target,{
    content:spec,theme:'default',layout:'modern',showSidebar:true,
    withDefaultFonts:false,telemetry:false,persistAuth:false,agent:{disabled:true},
    showDeveloperTools:'never',hideClientButton:true,hideTestRequestButton:false,
    hideDarkModeToggle:true,forceDarkModeState:'light',
    defaultHttpClient:{targetKey:'shell',clientKey:'curl'},
    customFetch:boundedFetch,
    // Intentionally no proxyUrl and no OAuth discovery or third-party plugin.
  });
}
