import { readFileSync } from "node:fs";

import { rootPath } from "./config";
import { loadCicdOtelRuntimeConfig } from "../native/cicd/otel-runtime-config";

const validatorSource = readFileSync(rootPath("scripts/native/cicd/feature-config-schema-warning.mjs"), "utf8").trimEnd();

export interface PacFeatureConfigSchemaStageOptions {
  readonly repositoryId: string;
  readonly consumer: string;
  readonly repoDirExpression: string;
  readonly renderedRootExpression: string;
  readonly ajvBundleExpression?: string | null;
}

export function renderPacFeatureConfigSchemaStage(options: PacFeatureConfigSchemaStageOptions): string {
  const otel = loadCicdOtelRuntimeConfig(options.repositoryId);
  return [
    "feature_config_schema_started_ms=\"$(date +%s%3N 2>/dev/null || date +%s000)\"",
    `export UNIDESK_FEATURE_CONFIG_REPO_DIR=${options.repoDirExpression}`,
    `export UNIDESK_FEATURE_CONFIG_RENDERED_ROOT=${options.renderedRootExpression}`,
    `export UNIDESK_PAC_CONSUMER=${shellSingle(options.consumer)}`,
    `export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=${shellSingle(otel.endpoint)}`,
    `export OTEL_SERVICE_NAME=${shellSingle(otel.serviceName)}`,
    `export OTEL_TRACES_SAMPLER_ARG=${shellSingle(String(otel.samplingRatio))}`,
    `export OTEL_EXPORTER_TIMEOUT_MS=${shellSingle(String(otel.timeoutMs))}`,
    ...(options.ajvBundleExpression === undefined || options.ajvBundleExpression === null
      ? []
      : [`export UNIDESK_AJV2020_BUNDLE=${options.ajvBundleExpression}`]),
    "if ! node --input-type=module <<'NODE_UNIDESK_FEATURE_CONFIG_SCHEMA'",
    validatorSource,
    "await runFeatureConfigSchemaValidation({",
    "  repoDir: process.env.UNIDESK_FEATURE_CONFIG_REPO_DIR,",
    "  renderedRoot: process.env.UNIDESK_FEATURE_CONFIG_RENDERED_ROOT,",
    "  consumer: process.env.UNIDESK_PAC_CONSUMER,",
    "});",
    "NODE_UNIDESK_FEATURE_CONFIG_SCHEMA",
    "then",
    "  printf '{\"event\":\"feature-config-schema-validation\",\"warning\":true,\"blocking\":false,\"code\":\"feature-config-validator-process-failure\",\"mutation\":false,\"valuesPrinted\":false}\\n' >&2",
    "fi",
    "if command -v ci_timing_emit >/dev/null 2>&1; then",
    "  ci_timing_emit feature-config-schema-validation succeeded \"$feature_config_schema_started_ms\"",
    "else",
    "  printf '{\"event\":\"ci.stage.timing\",\"stage\":\"feature-config-schema-validation\",\"status\":\"succeeded\",\"blocking\":false}\\n' >&2",
    "fi",
  ].join("\n");
}

function shellSingle(value: string): string {
  return `'${value.replaceAll("'", `'"'"'`)}'`;
}
