import { createDeviceGatewayRuntime } from "./runtime.mjs";

const listenEnabled = parseBoolean(
  process.env.DEVICE_GATEWAY_LISTEN_ENABLED,
  false,
);
const runtime = createDeviceGatewayRuntime({
  listenEnabled,
  healthHost: String(process.env.DEVICE_GATEWAY_HEALTH_HOST || "127.0.0.1"),
  healthPort: parsePort(process.env.DEVICE_GATEWAY_HEALTH_PORT, 18121),
  tcpHost: String(process.env.DEVICE_GATEWAY_TCP_HOST || "127.0.0.1"),
  tcpPort: parsePort(process.env.DEVICE_GATEWAY_TCP_PORT, 9921),
  maxConcurrentSessions: parsePositiveInt(
    process.env.DEVICE_GATEWAY_MAX_SESSIONS,
    100,
  ),
  sessionTimeoutMs: parsePositiveInt(
    process.env.DEVICE_GATEWAY_SESSION_TIMEOUT_MS,
    10000,
  ),
});

const addresses = await runtime.start();
console.log(JSON.stringify({
  event: "device_gateway_started",
  health: addresses.healthAddress,
  tcp: addresses.tcpAddress,
  publicIngress: "disabled",
  commandTransport: "disabled",
}));

process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);

async function shutdown() {
  await runtime.stop();
  process.exit(0);
}

function parsePort(value, fallback) {
  const parsed = Number(value || fallback);
  if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 65535) {
    throw new Error("device_gateway_port_invalid");
  }
  return parsed;
}

function parsePositiveInt(value, fallback) {
  const parsed = Number(value || fallback);
  if (!Number.isSafeInteger(parsed) || parsed < 1) {
    throw new Error("device_gateway_positive_integer_invalid");
  }
  return parsed;
}

function parseBoolean(value, fallback) {
  if (value === undefined || value === null || value === "") return fallback;
  const normalized = String(value).trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(normalized)) return true;
  if (["0", "false", "no", "off"].includes(normalized)) return false;
  throw new Error("device_gateway_boolean_invalid");
}
