#!/usr/bin/env bun
/*
 * SPEC: PJ2026-010103 HWPOD 服务；
 * PJ2026-01010305 71FREQ 预装 draft-2026-06-26-71freq-v03-hwpod-preinstall。
 * 责任: 启动拥有 runtime spec registry 与 Temporal 提交能力的 HWPOD API。
 */
import { createHwpodHttpApp } from "../../internal/hwpod/http.ts";
import { hwpodRuntime } from "../../internal/hwpod/runtime.ts";
import { createHwpodNodeWsRegistry } from "../../internal/cloud/hwpod-node-ws-registry.ts";

const runtime = hwpodRuntime();
const nodeRegistry = createHwpodNodeWsRegistry({ env: process.env });
const app = createHwpodHttpApp({ nodeOpsApiUrl: runtime.nodeOpsApiUrl, temporal: runtime.temporal, specRegistry: runtime.specRegistry, nodeRegistry, env: process.env });
const host = process.env.HWPOD_API_HOST || "0.0.0.0";
const port = positivePort(process.env.HWPOD_API_PORT, 6681);
const expectedNodeToken = required(process.env.HWPOD_NODE_WS_TOKEN, "HWPOD_NODE_WS_TOKEN");
const server = Bun.serve({
  hostname: host,
  port,
  idleTimeout: 120,
  fetch(request, bunServer) {
    const url = new URL(request.url);
    if (url.pathname !== "/v1/hwpod-node/ws") return app.fetch(request);
    const token = String(request.headers.get("x-hwpod-node-token") ?? url.searchParams.get("token") ?? "");
    if (token !== expectedNodeToken) return Response.json({ ok: false, error: { code: "hwpod_node_ws_token_invalid" }, valuesPrinted: false }, { status: 401 });
    return bunServer.upgrade(request, { data: { nodeRegistry } }) ? undefined : Response.json({ ok: false, status: "upgrade_required", valuesPrinted: false }, { status: 426 });
  },
  websocket: {
    open(socket: any) { socket.data.nodeRegistry.openBunSocket(socket); },
    message(socket: any, message: string | Buffer) { socket.data.nodeRegistry.handleBunMessage(socket, message); },
    close(socket: any) { socket.data.nodeRegistry.closeBunSocket(socket); },
  },
});
process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-hwpod-api", status: "listening", host, port: server.port, temporalNamespace: runtime.namespace, taskQueue: runtime.taskQueue, valuesPrinted: false })}\n`);
for (const signal of ["SIGINT", "SIGTERM"] as const) process.once(signal, async () => { server.stop(true); await app.close(); process.exit(0); });
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_API_PORT must be a valid port"); return parsed; }
function required(value: string | undefined, key: string) { const text = String(value ?? "").trim(); if (!text) throw new Error(`${key} is required`); return text; }
