import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import { resolve, extname, sep } from 'node:path';
const root = resolve(process.argv[2] || 'dist/site');
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.md': 'text/plain; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.json': 'application/json; charset=utf-8', '.gz': 'application/gzip', '.whl': 'application/octet-stream' };
const server = createServer(async (request, response) => {
  try {
    if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405); response.end(); return; }
    const path = decodeURIComponent(new URL(request.url, 'http://local').pathname);
    let file = resolve(root, `.${path}`);
    if (!file.startsWith(root + sep) && file !== root) { response.writeHead(403); response.end(); return; }
    let info = await stat(file);
    if (info.isDirectory()) {
      if (!path.endsWith('/')) { response.writeHead(308, { location: path + '/' }); response.end(); return; }
      file = resolve(file, 'index.html'); info = await stat(file);
    }
    const csp = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'";
    response.writeHead(200, { 'content-type': types[extname(file)] || 'application/octet-stream', 'content-length': info.size, 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer', ...(path.startsWith('/img-studio-lite/') ? {} : { 'content-security-policy': csp }), 'cache-control': 'no-cache' });
    response.end(request.method === 'HEAD' ? undefined : await readFile(file));
  } catch { response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); response.end('Not found'); }
});
server.listen(19390, '0.0.0.0', () => console.log(`Preview http://localhost:19390/ (${root})`));