#!/usr/bin/env bun
import { NativeConnection, Worker } from "@temporalio/worker";
import path from "node:path";

import { createHarnessRLActivities } from "../../internal/harnessrl/activities.ts";
import { harnessRLRuntime } from "../../internal/harnessrl/runtime.ts";

const runtime = harnessRLRuntime();
await runtime.registry.ensureSchema();
const connection = await NativeConnection.connect({ address: runtime.temporalAddress });
const worker = await Worker.create({ connection, namespace: runtime.temporalNamespace, taskQueue: runtime.taskQueue,
  workflowsPath: path.resolve(import.meta.dir, "../../internal/harnessrl/workflows.ts"), activities: createHarnessRLActivities({ registry: runtime.registry }) });
const healthPort = Number.parseInt(process.env.HARNESSRL_WORKER_HEALTH_PORT || "6676", 10);
const health = Bun.serve({ hostname: process.env.HARNESSRL_WORKER_HEALTH_HOST || "0.0.0.0", port: healthPort,
  fetch(request) { const pathname = new URL(request.url).pathname; return pathname === "/healthz" || pathname === "/readyz" || pathname === "/health/live" || pathname === "/health/ready" ? Response.json({ ok: true, serviceId: "hwlab-harnessrl-worker", namespace: runtime.temporalNamespace, taskQueue: runtime.taskQueue }) : new Response("not found", { status: 404 }); } });
process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-harnessrl-worker", status: "started", namespace: runtime.temporalNamespace, taskQueue: runtime.taskQueue, healthPort: health.port })}\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.registry.close(); }
