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

import { createWorkbenchActivities } from "../../internal/workbench/activities.ts";
import { workbenchRuntime } from "../../internal/workbench/runtime.ts";

const runtime = workbenchRuntime();
if (runtime.mode === "native-test") throw Object.assign(new Error("hwlab-workbench-worker requires WORKBENCH_MODE=agentrun-native or temporal"), { code: "workbench_worker_temporal_mode_required" });
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/workbench/workflows.ts"),
  activities: createWorkbenchActivities(runtime.application, { activity: runtime.activity!, eventPublisher: runtime.eventPublisher })
});
const healthPort = positivePort(process.env.WORKBENCH_WORKER_HEALTH_PORT, 6678);
const health = Bun.serve({
  hostname: process.env.WORKBENCH_WORKER_HEALTH_HOST || "0.0.0.0",
  port: healthPort,
  fetch(request) {
    const pathname = new URL(request.url).pathname;
    return ["/healthz", "/readyz", "/health/live", "/health/ready"].includes(pathname)
      ? Response.json({ ok: true, serviceId: "hwlab-workbench-worker", mode: runtime.mode, namespace: runtime.temporalNamespace, taskQueue: runtime.taskQueue })
      : new Response("not found", { status: 404 });
  }
});
process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-workbench-worker", status: "started", mode: runtime.mode, 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.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("WORKBENCH_WORKER_HEALTH_PORT must be a valid port"); return parsed; }
