#!/usr/bin/env bun
import path from "node:path";
import { NativeConnection, Worker } from "@temporalio/worker";
import { executeHwpodOperation } from "../../internal/hwpod/activities.ts";
import { hwpodRuntime } from "../../internal/hwpod/runtime.ts";

const runtime = hwpodRuntime();
const connection = await NativeConnection.connect({ address: runtime.address });
const worker = await Worker.create({ connection, namespace: runtime.namespace, taskQueue: runtime.taskQueue, workflowsPath: path.resolve(import.meta.dir, "../../internal/hwpod/workflows.ts"), activities: { executeHwpodOperation } });
const healthPort = positivePort(process.env.HWPOD_WORKER_HEALTH_PORT, 6682);
const health = Bun.serve({ hostname: process.env.HWPOD_WORKER_HEALTH_HOST || "0.0.0.0", port: healthPort, fetch(request) { return ["/healthz", "/readyz", "/health/live", "/health/ready"].includes(new URL(request.url).pathname) ? Response.json({ ok: true, serviceId: "hwlab-hwpod-worker", namespace: runtime.namespace, taskQueue: runtime.taskQueue, valuesPrinted: false }) : new Response("not found", { status: 404 }); } });
process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-hwpod-worker", status: "started", namespace: runtime.namespace, taskQueue: runtime.taskQueue, healthPort: health.port, valuesPrinted: false })}\n`);
for (const signal of ["SIGINT", "SIGTERM"] as const) process.once(signal, () => worker.shutdown());
try { await worker.run(); } finally { health.stop(true); await connection.close(); await runtime.temporal.close(); }
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_WORKER_HEALTH_PORT must be a valid port"); return parsed; }
