// Native helper injected into HWLAB runtime GitOps postprocess/verify scripts.
// It intentionally avoids imports so it can also run inside `node -` heredocs.
(function installRuntimeGitopsObservability(globalObject) {
  const prometheusOperatorKinds = new Set(["ServiceMonitor", "PrometheusRule", "PodMonitor", "Probe"]);

  function isObject(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value);
  }

  function isPrometheusOperatorResource(item) {
    return isObject(item)
      && typeof item.apiVersion === "string"
      && item.apiVersion.startsWith("monitoring.coreos.com/")
      && prometheusOperatorKinds.has(String(item.kind));
  }

  function prometheusOperatorDisabled(overlay) {
    return isObject(overlay?.observability) && overlay.observability.prometheusOperator === false;
  }

  function stripPrometheusOperatorResources(doc, overlay) {
    if (!prometheusOperatorDisabled(overlay)) return { docs: [doc], changed: false };
    if (isObject(doc) && doc.kind === "List" && Array.isArray(doc.items)) {
      const items = doc.items.filter((item) => !isPrometheusOperatorResource(item));
      return { docs: items.length > 0 ? [{ ...doc, items }] : [], changed: items.length !== doc.items.length };
    }
    return isPrometheusOperatorResource(doc) ? { docs: [], changed: true } : { docs: [doc], changed: false };
  }

  function prometheusOperatorResourceRef(item, file) {
    return {
      file,
      kind: item && item.kind,
      name: item && item.metadata && item.metadata.name,
      container: null,
    };
  }

  globalObject.unideskRuntimeGitopsObservability = {
    isPrometheusOperatorResource,
    stripPrometheusOperatorResources,
    prometheusOperatorResourceRef,
  };
})(globalThis);
