import { serve } from '@hono/node-server';
import { createApi } from './router.js';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const root=path.resolve(fileURLToPath(new URL('../public/',import.meta.url)));
const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.txt':'text/plain; charset=utf-8','.md':'text/plain; charset=utf-8'};
export function createServerApp(){
 const app=createApi({onInternalError:entry=>console.error(JSON.stringify(entry))});
 app.get('*',async c=>{
  const pathname=new URL(c.req.url).pathname;
  if(pathname.startsWith('/api/'))return c.json({ok:false,error:{code:'ROUTE_NOT_FOUND',message:'Маршрут не найден.'},requestId:c.get('requestId')},404);
  let relative;try{relative=decodeURIComponent(pathname==='/'?'/index.html':pathname).slice(1);}catch{return c.text('Bad path',400);}
  const file=path.resolve(root,relative);if(!file.startsWith(root+path.sep)&&file!==root)return c.text('Not found',404);
  if(!types[path.extname(file)]&&path.basename(file)!=='LICENSE')return c.text('Not found',404);
  try{return c.body(await readFile(file),200,{'Content-Type':types[path.extname(file)]||'text/plain; charset=utf-8'});}catch{return c.text('Not found',404);}
 });return app;
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
 const port=Number(process.env.PORT||8502),hostname=process.env.HOST||'127.0.0.1';
 if(!Number.isInteger(port)||port<1||port>65535)throw new Error('PORT must be 1..65535');
 const app=createServerApp();const server=serve({fetch:app.fetch,port,hostname},info=>console.log(`Hono: http://${hostname}:${info.port}`));
 server.requestTimeout=15000;server.headersTimeout=10000;server.keepAliveTimeout=5000;
 let stopping=false;function stop(){if(stopping)return;stopping=true;server.close(()=>process.exit(0));setTimeout(()=>{server.closeAllConnections();process.exit(1);},5000).unref();}
 process.on('SIGINT',stop);process.on('SIGTERM',stop);
}
