// Servidor estático do Buenas-New (SSG): gzip + cache. Uso: node serve.js [dir] [porta]
const http=require('http'),fs=require('fs'),path=require('path'),zlib=require('zlib')
const ROOT=path.resolve(process.argv[2]||'dist'), PORT=+(process.argv[3]||process.env.PORT||8092)
const M={'.html':'text/html;charset=utf-8','.css':'text/css','.js':'application/javascript','.webp':'image/webp','.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.svg':'image/svg+xml','.woff2':'font/woff2','.woff':'font/woff','.ttf':'font/ttf','.xml':'application/xml','.txt':'text/plain','.json':'application/json','.ico':'image/x-icon'}
http.createServer((req,res)=>{
  let p=decodeURIComponent((req.url||'/').split('?')[0])
  if(p.includes('..')){res.writeHead(400);return res.end()}
  let fp=path.join(ROOT,p)
  try{ if(fs.statSync(fp).isDirectory()) fp=path.join(fp,'index.html') }catch(e){}
  fs.readFile(fp,(e,d)=>{
    if(e){ // fallback SPA-ish: 404 -> home 404 page? aqui só 404
      res.writeHead(404,{'Content-Type':'text/html;charset=utf-8'}); return res.end('<h1>404</h1>')
    }
    const ext=path.extname(fp).toLowerCase(), mime=M[ext]||'application/octet-stream'
    const immut=/\.(css|js|webp|png|jpe?g|woff2?|ttf|svg|ico)$/.test(fp)
    const h={'Content-Type':mime,'Cache-Control':immut?'public,max-age=31536000,immutable':'no-cache','X-Content-Type-Options':'nosniff'}
    if(/text|javascript|json|xml|svg/.test(mime)&&/gzip/.test(req.headers['accept-encoding']||'')){
      h['Content-Encoding']='gzip'; res.writeHead(200,h); res.end(zlib.gzipSync(d))
    } else { res.writeHead(200,h); res.end(d) }
  })
}).listen(PORT,'0.0.0.0',()=>console.log('Buenas-New SSG servindo',ROOT,'na porta',PORT))
