"use strict";

const fs = require("node:fs");
const http = require("node:http");
const path = require("node:path");
const os = require("node:os");

const ROOT = __dirname;
const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8" };

function json(response, status, value) {
  response.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
  response.end(JSON.stringify(value));
}

function createApp() {
  return http.createServer((request, response) => {
    const url = new URL(request.url, "http://localhost");
    if (request.method !== "GET") return json(response, 405, { ok: false, error: "method_not_allowed" });
    if (url.pathname === "/api/status") {
      return json(response, 200, {
        ok: true,
        node_id: process.env.GUANGHU_NODE_ID || "JD-FD-PRIMARY",
        role: "fifth-domain-primary",
        service: "jd-app-hub",
        uptime_seconds: Math.floor(process.uptime()),
        load_1m: Number(os.loadavg()[0].toFixed(2)),
        memory_used_percent: Number((((os.totalmem() - os.freemem()) / os.totalmem()) * 100).toFixed(1)),
        timestamp: new Date().toISOString()
      });
    }
    const relative = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
    if (!/^(index\.html|styles\.css|app\.js)$/.test(relative)) return json(response, 404, { ok: false, error: "not_found" });
    const file = path.join(ROOT, relative);
    response.writeHead(200, { "Content-Type": TYPES[path.extname(file)] || "application/octet-stream", "Cache-Control": relative === "index.html" ? "no-cache" : "public, max-age=3600" });
    fs.createReadStream(file).pipe(response);
  });
}

if (require.main === module) {
  const host = process.env.HUB_HOST || "127.0.0.1";
  const port = Number(process.env.HUB_PORT || 8088);
  createApp().listen(port, host, () => console.log(`JD app hub listening on ${host}:${port}`));
}

module.exports = { createApp };
