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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

if ! command -v helm >/dev/null 2>&1; then
  echo "helm not available, skipping chart lint/render test"
  exit 0
fi

helm lint "$ROOT_DIR/helm"
rendered="$(mktemp)"
trap 'rm -f "$rendered"' EXIT

helm template shenron "$ROOT_DIR/helm" -f "$ROOT_DIR/helm/models.yaml" >"$rendered"

if ! grep -q "app.kubernetes.io/component: router" "$rendered"; then
  echo "expected router resources to be rendered" >&2
  exit 1
fi

if ! grep -q -- "--service-discovery" "$rendered"; then
  echo "expected router deployments to enable service discovery" >&2
  exit 1
fi

if ! grep -q "http://shenron-router-" "$rendered"; then
  echo "expected onwards targets to point to router services" >&2
  exit 1
fi

if ! grep -q "name: shenron-replica-manager" "$rendered"; then
  echo "expected replica manager resources to be rendered" >&2
  exit 1
fi

if ! grep -q "REPLICA_MANAGER_TOKEN" "$rendered"; then
  echo "expected replica manager auth env var wiring" >&2
  exit 1
fi

if ! grep -q "app.kubernetes.io/component: scouter-reporter" "$rendered"; then
  echo "expected scouter reporter resources to be renderable" >&2
  exit 1
fi

if ! grep -q "SCOUTER_MODE" "$rendered"; then
  echo "expected scouter reporter env wiring" >&2
  exit 1
fi

if ! grep -q "SCOUTER_INGEST_API_KEY" "$rendered"; then
  echo "expected scouter reporter API key secret wiring" >&2
  exit 1
fi

if ! grep -q 'value: "http://shenron-prometheus:9090"' "$rendered"; then
  echo "expected scouter reporter to target in-cluster prometheus service" >&2
  exit 1
fi

echo "helm chart lint/template succeeded"
