#!/usr/bin/env bun
import path from "node:path";

const host = process.env.HWPOD_WEB_HOST || "0.0.0.0";
const port = positivePort(process.env.HWPOD_WEB_PORT, 8080);
const apiUrl = requiredUrl(process.env.HWPOD_API_URL, "HWPOD_API_URL");
const root = path.resolve(process.env.HWPOD_WEB_ROOT || "web/hwlab-cloud-web/hwpod/dist");

const server = Bun.serve({
  hostname: host,
  port,
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === "/health/live") return Response.json({ ok: true, serviceId: "hwlab-hwpod-web", status: "live", valuesPrinted: false });
    if (url.pathname === "/health/ready" || url.pathname.startsWith("/v1/")) return proxyRequest(request, apiUrl, url);
    const relativePath = url.pathname === "/" ? "index.html" : decodeURIComponent(url.pathname.replace(/^\/+/, ""));
    const filePath = path.resolve(root, relativePath);
    if (!filePath.startsWith(`${root}${path.sep}`) && filePath !== path.join(root, "index.html")) return new Response("not found", { status: 404 });
    const file = Bun.file(filePath);
    if (await file.exists()) return new Response(file, { headers: { "cache-control": relativePath === "index.html" ? "no-store" : "public, max-age=3600" } });
    return new Response("not found", { status: 404 });
  },
});

process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-hwpod-web", status: "listening", host, port: server.port, apiAuthority: apiUrl, valuesPrinted: false })}\n`);
for (const signal of ["SIGINT", "SIGTERM"] as const) process.once(signal, () => { server.stop(true); process.exit(0); });

async function proxyRequest(request: Request, baseUrl: string, sourceUrl: URL) {
  const target = new URL(`${sourceUrl.pathname}${sourceUrl.search}`, baseUrl);
  const headers = new Headers(request.headers);
  headers.delete("host");
  return fetch(target, { method: request.method, headers, body: request.body, redirect: "manual", signal: request.signal });
}
function requiredUrl(value: string | undefined, name: string) { const parsed = new URL(String(value ?? "")); if (!/^https?:$/u.test(parsed.protocol)) throw new Error(`${name} must be an HTTP URL`); return parsed.toString().replace(/\/$/u, ""); }
function positivePort(value: string | undefined, fallback: number) { const parsed = Number.parseInt(String(value ?? fallback), 10); if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) throw new Error("HWPOD_WEB_PORT must be a valid port"); return parsed; }
