#!/usr/bin/env bun
// SPEC: PJ2026-01060508 Web哨兵 draft-2026-06-25-p0-web-probe-sentinel.
// SPEC: PJ2026-01060508 Web哨兵 draft-2026-06-26-p9-multi-web-probe-sentinel.
// Responsibility: Bun entrypoint for the web-probe sentinel HTTP wrapper service.
import { hwlabRuntimeLaneSpecForNode, isHwlabRuntimeLane } from "./src/hwlab-node-lanes";
import { createWebProbeSentinelService, startWebProbeSentinelHttpService } from "./src/hwlab-node-web-sentinel-service";

const args = process.argv.slice(2);
const node = requiredOption("--node");
const lane = requiredOption("--lane");
const sentinelId = optionValue("--sentinel") ?? optionValue("--sentinel-id") ?? null;
if (!isHwlabRuntimeLane(lane)) throw new Error(`web-probe sentinel service only supports HWLAB runtime lanes, got ${lane}`);
const spec = hwlabRuntimeLaneSpecForNode(lane, node);
const stateRootOverride = optionValue("--state-root");
const hostOverride = optionValue("--host");
const portRaw = optionValue("--port");
const portOverride = portRaw === undefined ? undefined : Number(portRaw);
if (portOverride !== undefined && (!Number.isInteger(portOverride) || portOverride <= 0 || portOverride > 65535)) throw new Error("--port must be 1-65535");
const schedulerEnabled = !args.includes("--scheduler-disabled");
const service = createWebProbeSentinelService({ spec, sentinelId, stateRootOverride, hostOverride, portOverride, schedulerEnabled });

if (args.includes("--once")) {
  const health = service.health();
  console.log(JSON.stringify(health, null, 2));
  service.close();
  process.exit(health.ok === true ? 0 : 1);
}

const server = startWebProbeSentinelHttpService(service);
console.log(JSON.stringify({
  ok: true,
  command: "web-probe-sentinel-service",
  node,
  lane,
  sentinelId: service.config.sentinelId,
  url: server.url,
  schedulerEnabled,
  health: service.health(),
  valuesRedacted: true,
}, null, 2));

process.on("SIGTERM", () => {
  server.stop();
  service.close();
  process.exit(0);
});
process.on("SIGINT", () => {
  server.stop();
  service.close();
  process.exit(0);
});

await new Promise(() => undefined);

function optionValue(name: string): string | undefined {
  const index = args.indexOf(name);
  return index === -1 ? undefined : args[index + 1];
}

function requiredOption(name: string): string {
  const value = optionValue(name);
  if (value === undefined || value.length === 0) throw new Error(`${name} is required`);
  return value;
}
