// Serves the built dist/ (app) and dist-media/ (media, with CORS + Range) on two
// ports — a local stand-in for Pages + R2, so the static-build E2E exercises the
// cross-origin media path exactly as production will (CORS for the WebGL dream
// shader, Range for video scrubbing).
//
// Env: DIST_DIR (app root), MEDIA_DIR_E2E (media root). Ports: app 8077, media 8078.
import http from "node:http";
import { createReadStream, statSync } from "node:fs";
import { join, extname, normalize } from "node:path";

const TYPES = {
  ".html": "text/html", ".js": "text/javascript", ".json": "application/json",
  ".css": "text/css", ".mp4": "video/mp4", ".mp3": "audio/mpeg",
};

function serve(root, port, cors, indexFallback) {
  http.createServer((req, res) => {
    if (cors) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Accept-Ranges", "bytes"); }
    let p = decodeURIComponent(req.url.split("?")[0]);
    if (p.endsWith("/")) p += "index.html";
    // contain to root (no path traversal)
    const file = normalize(join(root, p));
    if (!file.startsWith(normalize(root))) { res.writeHead(403); return res.end("forbidden"); }
    try {
      const st = statSync(file);
      res.setHeader("Content-Type", TYPES[extname(file)] || "application/octet-stream");
      const range = req.headers.range;                       // honor Range for video scrub
      if (range && /^bytes=/.test(range)) {
        const [s, e] = range.replace("bytes=", "").split("-");
        const start = +s, end = e ? +e : st.size - 1;
        res.writeHead(206, {
          "Content-Range": `bytes ${start}-${end}/${st.size}`,
          "Content-Length": end - start + 1,
        });
        createReadStream(file, { start, end }).pipe(res);
      } else {
        res.writeHead(200, { "Content-Length": st.size });
        createReadStream(file).pipe(res);
      }
    } catch {
      res.writeHead(404); res.end("not found");
    }
  }).listen(port);
}

serve(process.env.DIST_DIR, 8077, false);
serve(process.env.MEDIA_DIR_E2E, 8078, true);
console.log("static app :8077  media(cors) :8078");
