import { readFileSync } from "node:fs";
import path from "node:path";

export function runtimeGitopsScriptsConfigMap({ overlay, scriptsDir, featureConfigValidatorPath = null, ajvBundlePath = null, namespace, configMapName }) {
  const data = {
    "runtime-gitops-overlay.json": `${JSON.stringify({
      runtimePath: requiredString(overlay.runtimePath, "overlay.runtimePath"),
      observability: objectOr(overlay.observability),
      codeAgentRuntime: objectOr(overlay.codeAgentRuntime),
    })}\n`,
  };
  for (const name of [
    "runtime-gitops-observability.mjs",
    "runtime-gitops-postprocess.mjs",
    "runtime-gitops-verify.mjs",
  ]) {
    data[name] = readFileSync(path.join(scriptsDir, name), "utf8");
  }
  const featureConfigValidator = optionalFile(featureConfigValidatorPath ?? path.join(scriptsDir, "feature-config-schema-warning.mjs"));
  if (featureConfigValidator !== null) data["feature-config-schema-warning.mjs"] = featureConfigValidator;
  const ajvBundle = optionalFile(ajvBundlePath ?? path.join(scriptsDir, "ajv2020.min.js"));
  if (ajvBundle !== null) data["ajv2020.min.js"] = ajvBundle;
  return {
    apiVersion: "v1",
    kind: "ConfigMap",
    metadata: {
      name: configMapName,
      namespace,
      labels: {
        "app.kubernetes.io/name": "hwlab-runtime-gitops-scripts",
        "app.kubernetes.io/part-of": "unidesk-hwlab-control-plane",
        "app.kubernetes.io/managed-by": "unidesk-host-gitops",
        "hwlab.pikastech.local/node": overlay.nodeId ?? null,
        "hwlab.pikastech.local/lane": overlay.lane ?? null,
      },
    },
    data,
  };
}

function requiredString(value, pathLabel) {
  if (typeof value !== "string" || value.length === 0) throw new Error(`${pathLabel} must be a non-empty string`);
  return value;
}

function objectOr(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}

function optionalFile(file) {
  try {
    return readFileSync(file, "utf8");
  } catch {
    return null;
  }
}
