#!/usr/bin/env bash
# gen-configs.sh - generate metrics-config and prometheus-config from cluster IDs in test.env
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/test-common.sh"

OUTPUT_DIR="${GENERATED_CONFIG_DIR}"
mkdir -p "${OUTPUT_DIR}"

# Quote arbitrary strings safely for single-quoted YAML scalars.
yaml_quote() {
  local value="${1-}"
  value="${value//\'/\'\'}"
  printf "'%s'" "${value}"
}

# Select projectId by service plan
get_project_id() {
  local service_plan="$1"
  case "${service_plan}" in
    Dedicated) echo "${PROJECT_ID_DEDICATED:-}" ;;
    Premium)   echo "${PROJECT_ID_PREMIUM:-}" ;;
    Essential) echo "${PROJECT_ID_ESSENTIAL:-}" ;;
    Starter)   echo "${PROJECT_ID_STARTER:-}" ;;
    *)         echo "" ;;
  esac
}

get_region() {
  local service_plan="$1"
  local env_name="CLUSTER_REGION_$(echo "${service_plan}" | tr '[:lower:]' '[:upper:]')"
  local value="${!env_name:-}"
  if [[ -n "${value}" ]]; then
    echo "${value}"
    return
  fi

  echo "${CLUSTER_REGION}"
}

get_provider() {
  local service_plan="$1"
  local env_name="CLUSTER_CLOUD_PROVIDER_$(echo "${service_plan}" | tr '[:lower:]' '[:upper:]')"
  local value="${!env_name:-}"
  if [[ -n "${value}" ]]; then
    echo "${value}"
    return
  fi

  echo "${CLUSTER_CLOUD_PROVIDER}"
}

get_regional_data_host() {
  local service_plan="$1"
  local region; region="$(get_region "${service_plan}")"
  local provider; provider="$(get_provider "${service_plan}")"

  case "${service_plan}" in
    Dedicated)
      echo "www.ds.${region}-staging.${provider}.observability.tidbcloud.com"
      ;;
    Premium)
      echo "www.ds.${region}-premium.${provider}.observability.tidbcloud.com"
      ;;
    Essential|Starter)
      echo "www.ds.${region}-serverless.${provider}.observability.tidbcloud.com"
      ;;
    *)
      echo "www.ds.${region}.${provider}.observability.tidbcloud.com"
      ;;
  esac
}

write_local_regional_mappings() {
  local wrote=false

  for service_plan in Dedicated Premium Essential Starter; do
    local env_name="LOCAL_TEST_REGIONAL_SERVER_URL_$(echo "${service_plan}" | tr '[:lower:]' '[:upper:]')"
    local local_url="${!env_name:-}"
    if [[ -z "${local_url}" ]]; then
      continue
    fi

    if [[ "${wrote}" == "false" ]]; then
      cat << EOF
  localTestRegionalServerUrlMappings:
EOF
      wrote=true
    fi

    cat << EOF
    - host: $(yaml_quote "$(get_regional_data_host "${service_plan}")")
      url: $(yaml_quote "${local_url}")
EOF
  done
}

# Shared o11y config block writer
write_o11y_block() {
  cat << EOF
o11yGlobalServer:
  url: https://www.gs.us-west-2.aws.observability.tidbcloud.com
  domainSuffix: observability.tidbcloud.com
  bizType: dev-tidbcloud
  bizTypeConfigs:
    dedicated: dev-tidbcloud
    premium: dev-tidbcloud-nextgen
    starter: dev-devtier
    essential: dev-devtier
  auth0Domain: tidb-soc2.us.auth0.com
  auth0Audience: https://tidb-soc2.us.auth0.com/api/v2/
  auth0ClientID: PjV8VvZDfw1yCr7xVC4W386iMnClp4hn
  auth0ClientSecret: $(yaml_quote "${AUTH0_CLIENT_SECRET}")
  regionalDataServerUriPrefix: /internal/metrics
  metricsApiUrl: https://us-west-2.nightly.shared.aws.tidbcloud.com
  localTestEnabled: ${LOCAL_TEST_ENABLED:-false}
  localTestGlobalServerUrl: $(yaml_quote "${LOCAL_TEST_GLOBAL_SERVER_URL:-}")
  localTestRegionalServerUrl: $(yaml_quote "${LOCAL_TEST_REGIONAL_SERVER_URL:-}")
EOF
  write_local_regional_mappings
}

# Generate metrics-config-<ServicePlan>-<id>.yaml
gen_metrics_config() {
  local cluster_id="$1"
  local service_plan="$2"
  local has_components="$3"
  local name="test-$(echo "${service_plan}" | tr '[:upper:]' '[:lower:]')"
  local project_id; project_id="$(get_project_id "${service_plan}")"
  local region; region="$(get_region "${service_plan}")"
  local provider; provider="$(get_provider "${service_plan}")"
  local out="${OUTPUT_DIR}/metrics-config-${service_plan}-${cluster_id}.yaml"

  cat > "${out}" << EOF
server:
  logLevel: info
  grpcPort: 10000
  metricsPort: 9090
  metricsListenAddr: 0.0.0.0:8080
$(write_o11y_block)
targetClusters:
  - id: $(yaml_quote "${cluster_id}")
    name: $(yaml_quote "${name}")
    cloudProviderName: $(yaml_quote "${provider}")
    regionName: $(yaml_quote "${region}")
    tenantId: $(yaml_quote "${TENANT_ID}")
    projectId: $(yaml_quote "${project_id}")
    servicePlan: $(yaml_quote "${service_plan}")
EOF

  if [[ "${has_components}" == "true" ]]; then
    cat >> "${out}" << EOF
    components:
      - componentType: "COMPONENT_TYPE_TIDB"
        cpuNum: ${DEDICATED_TIDB_CPU}
      - componentType: "COMPONENT_TYPE_TIKV"
        cpuNum: ${DEDICATED_TIKV_CPU}
      - componentType: "COMPONENT_TYPE_PD"
        cpuNum: ${DEDICATED_PD_CPU}
EOF
  fi
  echo "  generated: $(basename "${out}")"
}

# Generate prometheus-config-<ServicePlan>-<id>.yaml
gen_prometheus_config() {
  local cluster_id="$1"
  local service_plan="$2"
  local has_components="$3"
  local name="test-$(echo "${service_plan}" | tr '[:upper:]' '[:lower:]')"
  local project_id; project_id="$(get_project_id "${service_plan}")"
  local region; region="$(get_region "${service_plan}")"
  local provider; provider="$(get_provider "${service_plan}")"
  local out="${OUTPUT_DIR}/prometheus-config-${service_plan}-${cluster_id}.yaml"

  cat > "${out}" << EOF
server:
  logLevel: info
  grpcPort: 10001
  metricsPort: 9091
  metricsListenAddr: 0.0.0.0:8080
$(write_o11y_block)
targetClusters:
  - id: $(yaml_quote "${cluster_id}")
    name: $(yaml_quote "${name}")
    cloudProviderName: $(yaml_quote "${provider}")
    regionName: $(yaml_quote "${region}")
    tenantId: $(yaml_quote "${TENANT_ID}")
    projectId: $(yaml_quote "${project_id}")
    servicePlan: $(yaml_quote "${service_plan}")
EOF

  if [[ "${has_components}" == "true" ]]; then
    cat >> "${out}" << EOF
    components:
      - componentType: "COMPONENT_TYPE_TIDB"
        cpuNum: ${DEDICATED_TIDB_CPU}
      - componentType: "COMPONENT_TYPE_TIKV"
        cpuNum: ${DEDICATED_TIKV_CPU}
      - componentType: "COMPONENT_TYPE_PD"
        cpuNum: ${DEDICATED_PD_CPU}
EOF
  fi

  cat >> "${out}" << EOF
prometheusTokenMappings:
  - clusterID: $(yaml_quote "${cluster_id}")
    token: $(yaml_quote "${PROMETHEUS_TOKEN}")
EOF
  echo "  generated: $(basename "${out}")"
}

# Main flow
echo "Generating test configuration files..."

for cluster_entry in \
  "${CLUSTER_ID_DEDICATED}:Dedicated:true" \
  "${CLUSTER_ID_PREMIUM}:Premium:false" \
  "${CLUSTER_ID_ESSENTIAL}:Essential:false" \
  "${CLUSTER_ID_STARTER}:Starter:false"; do
  IFS=: read -r cluster_id service_plan has_components <<< "${cluster_entry}"
  if [[ -z "${cluster_id}" ]]; then
    echo "  skipping ${service_plan}: cluster_id is empty, you can retry later"
    continue
  fi

  gen_metrics_config "${cluster_id}" "${service_plan}" "${has_components}"
  gen_prometheus_config "${cluster_id}" "${service_plan}" "${has_components}"
done

echo ""
echo "✅ Configuration files written to ${OUTPUT_DIR}/"
echo "   total: $(ls "${OUTPUT_DIR}"/metrics-config-*.yaml "${OUTPUT_DIR}"/prometheus-config-*.yaml 2>/dev/null | wc -l) files"
