#!/usr/bin/env bun
import { createCloudApiBunServer } from "../../internal/cloud/bun-server.ts";
import { applyCloudApiImageEnv, parsePort, parseTimeout } from "./runtime-options.ts";

const host = process.env.HWLAB_CLOUD_API_HOST || "0.0.0.0";
const port = parsePort(process.env.HWLAB_CLOUD_API_PORT, parsePort(process.env.PORT, 6667));
const codeAgentTimeoutMs = parseTimeout(process.env.HWLAB_CODE_AGENT_TIMEOUT_MS, 1200000, {
  min: 1000,
  max: 2400000
});
const codeAgentHardTimeoutMs = parseTimeout(process.env.HWLAB_CODE_AGENT_HARD_TIMEOUT_MS, Math.max(1200000, codeAgentTimeoutMs * 4), {
  min: codeAgentTimeoutMs,
  max: 3600000
});
applyCloudApiImageEnv(process.env);

const runtime = await createCloudApiBunServer({
  host,
  port,
  codeAgentTimeoutMs,
  codeAgentHardTimeoutMs
});

process.stdout.write(
  `${JSON.stringify({
    serviceId: "hwlab-cloud-api",
    status: "listening",
    host,
    port: runtime.port,
    hwpodNodeWs: "/v1/hwpod-node/ws"
  })}\n`
);

for (const signal of ["SIGINT", "SIGTERM"]) {
  process.on(signal, () => {
    runtime.stop();
    process.exit(0);
  });
}
