/*
 * SPEC: PJ2026-010103 HWPOD 服务；
 * PJ2026-01010305 71FREQ 预装 draft-2026-06-26-71freq-v03-hwpod-preinstall。
 * 实现引用: draft-2026-07-20-hwpod-temporal-split。
 * 责任: HWPOD API 的 Temporal、node-ops 与 spec registry 配置解析。
 */

import { createHwpodTemporalGateway } from "./temporal.ts";
import { hwpodSpecRegistryFromEnv } from "./spec-registry.ts";

export function hwpodRuntime(env: Record<string, string | undefined> = process.env) {
  const address = String(env.HWPOD_TEMPORAL_ADDRESS ?? env.TEMPORAL_ADDRESS ?? "").trim();
  const namespace = String(env.HWPOD_TEMPORAL_NAMESPACE ?? "unidesk").trim();
  const taskQueue = String(env.HWPOD_TEMPORAL_TASK_QUEUE ?? "hwlab-v03-hwpod").trim();
  const nodeOpsApiUrl = String(env.HWPOD_NODE_OPS_API_URL ?? "").trim().replace(/\/+$/u, "");
  if (!nodeOpsApiUrl) throw codedError("hwpod_node_ops_api_url_required", "HWPOD_NODE_OPS_API_URL is required");
  return {
    address,
    namespace,
    taskQueue,
    nodeOpsApiUrl,
    temporal: createHwpodTemporalGateway({ address, namespace, taskQueue }),
    specRegistry: hwpodSpecRegistryFromEnv(env),
  };
}

function codedError(code: string, message: string) { return Object.assign(new Error(message), { code }); }
