#!/usr/bin/env bash
set -Eeuo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
LT="$ROOT/deploy/oke/load-test"
RUNTIME_ENV="$LT/.env.runtime"
LF_ENV="$LT/.env.langfuse"

log(){ printf '[langfuse-sync] %s\n' "$*"; }
die(){ printf '[langfuse-sync] ERROR: %s\n' "$*" >&2; exit 1; }

# IMPORTANT: do not `source .env.runtime` here. It contains backend OCI settings
# (OCI_AUTH_MODE, OCI_PROFILE, OCI_CLI_PROFILE, etc.) that can change the OCI CLI
# exec-plugin environment used by kubectl/kubeconfig.
read_env_value() {
  local file="$1" key="$2" default_value="${3:-}"
  local value=""
  if [[ -f "$file" ]]; then
    value="$(sed -n -E "s/^${key}=(.*)$/\\1/p" "$file" | tail -n 1)"
    value="${value%$'\r'}"
    if [[ "$value" == \"*\" && "$value" == *\" ]]; then value="${value:1:${#value}-2}"; fi
    if [[ "$value" == \'*\' && "$value" == *\' ]]; then value="${value:1:${#value}-2}"; fi
  fi
  printf '%s\n' "${value:-$default_value}"
}

LF_NS="${LANGFUSE_NAMESPACE:-$(read_env_value "$RUNTIME_ENV" LANGFUSE_NAMESPACE langfuse)}"
APP_NS="${K8S_NAMESPACE:-$(read_env_value "$RUNTIME_ENV" K8S_NAMESPACE agent-load-test)}"
LF_SECRET="${LANGFUSE_RUNTIME_SECRET:-langfuse-runtime}"
CLIENT_SECRET="${LANGFUSE_CLIENT_SECRET:-langfuse-client}"
LF_HOST="${LANGFUSE_HOST:-$(read_env_value "$RUNTIME_ENV" LANGFUSE_HOST "http://langfuse-web.${LF_NS}.svc.cluster.local:3000")}"

command -v kubectl >/dev/null 2>&1 || die "kubectl not found"

log "Kubernetes context: $(kubectl config current-context 2>/dev/null || echo '<unknown>')"
log "Langfuse namespace: $LF_NS"
log "Backend namespace: $APP_NS"

# Do not hide kubectl errors. A credentials/context problem is not a missing Secret.
set +e
secret_err="$(mktemp)"
kubectl -n "$LF_NS" get secret "$LF_SECRET" >/dev/null 2>"$secret_err"
rc=$?
set -e
if (( rc != 0 )); then
  msg="$(cat "$secret_err")"
  rm -f "$secret_err"
  echo "$msg" >&2
  echo >&2
  log "Secrets visible in namespace '$LF_NS':"
  kubectl -n "$LF_NS" get secrets 2>&1 || true
  echo >&2
  log "Langfuse web Secret references:"
  kubectl -n "$LF_NS" get deployment langfuse-web \
    -o jsonpath='{.spec.template.spec.containers[0].envFrom[*].secretRef.name}{"\n"}' 2>&1 || true
  die "cannot read Secret/$LF_SECRET in namespace $LF_NS (kubectl rc=$rc). See the kubectl error above; this may be authentication/context rather than a missing Secret."
fi
rm -f "$secret_err"

get_secret(){
  local key="$1"
  local encoded
  encoded="$(kubectl -n "$LF_NS" get secret "$LF_SECRET" -o "jsonpath={.data.${key}}")"
  [[ -n "$encoded" ]] && printf '%s' "$encoded" | base64 -d
}

PUBLIC_KEY="$(get_secret LANGFUSE_INIT_PROJECT_PUBLIC_KEY || true)"
SECRET_KEY="$(get_secret LANGFUSE_INIT_PROJECT_SECRET_KEY || true)"
[[ -n "$PUBLIC_KEY" ]] || PUBLIC_KEY="$(get_secret LANGFUSE_PUBLIC_KEY || true)"
[[ -n "$SECRET_KEY" ]] || SECRET_KEY="$(get_secret LANGFUSE_SECRET_KEY || true)"

# Last-resort local fallback: the same values generated by prepare_env.py.
if [[ -z "$PUBLIC_KEY" && -f "$LF_ENV" ]]; then
  PUBLIC_KEY="$(read_env_value "$LF_ENV" LANGFUSE_INIT_PROJECT_PUBLIC_KEY '')"
fi
if [[ -z "$SECRET_KEY" && -f "$LF_ENV" ]]; then
  SECRET_KEY="$(read_env_value "$LF_ENV" LANGFUSE_INIT_PROJECT_SECRET_KEY '')"
fi

[[ -n "$PUBLIC_KEY" ]] || die "Langfuse public key is empty"
[[ -n "$SECRET_KEY" ]] || die "Langfuse secret key is empty"

kubectl create namespace "$APP_NS" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
kubectl -n "$APP_NS" create secret generic "$CLIENT_SECRET" \
  --from-literal=LANGFUSE_PUBLIC_KEY="$PUBLIC_KEY" \
  --from-literal=LANGFUSE_SECRET_KEY="$SECRET_KEY" \
  --from-literal=LANGFUSE_HOST="$LF_HOST" \
  --dry-run=client -o yaml | kubectl apply -f - >/dev/null

log "Secret/$CLIENT_SECRET synchronized into namespace $APP_NS."
log "Public key: ${PUBLIC_KEY:0:10}... (secret key not printed)"
