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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel)"

# Source the adoption script to get access to functions
source "${SCRIPT_DIR}/adopt-alertmanager-regional.sh"

tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

# --- Test 1: adoption_capture_workload_snapshot ---

echo "Test 1: adoption_capture_workload_snapshot captures all expected workloads"

# Stub kubectl to return mock pod data for all monitored namespaces/prefixes
kubectl() {
  case "$*" in
    *"default get pods"*)
      cat <<'JSON'
{
  "items": [
    {
      "metadata": {"name": "alertmanager-alert-regional-0", "uid": "uid-am-0"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "alertmanager", "restartCount": 0}]}
    },
    {
      "metadata": {"name": "alertmanager-alert-regional-1", "uid": "uid-am-1"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "alertmanager", "restartCount": 2}]}
    }
  ]
}
JSON
      ;;
    *"observability get pods"*)
      cat <<'JSON'
{
  "items": [
    {
      "metadata": {"name": "regionalserver-0", "uid": "uid-rs-0"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "regionalserver", "restartCount": 1}]}
    },
    {
      "metadata": {"name": "data-server-0", "uid": "uid-ds-0"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "data-server", "restartCount": 0}, {"name": "sidecar", "restartCount": 3}]}
    },
    {
      "metadata": {"name": "loki-ha-backend-0", "uid": "uid-loki-back-0"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "loki", "restartCount": 0}]}
    },
    {
      "metadata": {"name": "vmselect-vmcluster-0", "uid": "uid-vmsel-0"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "vmselect", "restartCount": 1}]}
    },
    {
      "metadata": {"name": "other-pod", "uid": "uid-other"},
      "status": {"phase": "Running", "containerStatuses": [{"name": "other", "restartCount": 0}]}
    }
  ]
}
JSON
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

snapshot_file="$tmpdir/snapshot1.txt"
adoption_capture_workload_snapshot "$snapshot_file"

if [[ ! -s "$snapshot_file" ]]; then
  echo "ERROR: Snapshot file is empty" >&2
  exit 1
fi

# Verify alertmanager pods captured
if ! grep -q "^default|alertmanager-alert-regional-0|uid-am-0|Running|alertmanager:0$" "$snapshot_file"; then
  echo "ERROR: Missing or incorrect alertmanager-alert-regional-0 entry" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

if ! grep -q "^default|alertmanager-alert-regional-1|uid-am-1|Running|alertmanager:2$" "$snapshot_file"; then
  echo "ERROR: Missing or incorrect alertmanager-alert-regional-1 entry" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

# Verify observability workloads captured
if ! grep -q "^observability|regionalserver-0|uid-rs-0|Running|regionalserver:1$" "$snapshot_file"; then
  echo "ERROR: Missing or incorrect regionalserver-0 entry" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

if ! grep -q "^observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:3$" "$snapshot_file"; then
  echo "ERROR: Missing or incorrect data-server-0 entry with multi-container restart counts" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

if ! grep -q "^observability|loki-ha-backend-0|" "$snapshot_file"; then
  echo "ERROR: Missing loki-ha-backend-0 entry" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

if ! grep -q "^observability|vmselect-vmcluster-0|" "$snapshot_file"; then
  echo "ERROR: Missing vmselect-vmcluster-0 entry" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

# Verify other-pod is NOT captured (doesn't match any prefix)
if grep -q "other-pod" "$snapshot_file"; then
  echo "ERROR: Should not capture pods that don't match expected prefixes" >&2
  cat "$snapshot_file" >&2
  exit 1
fi

echo "  ✓ Snapshot captures all expected workloads with correct restart counts"

# --- Test 2: adoption_validate_cluster_context ---

echo "Test 2: adoption_validate_cluster_context"

kubectl() {
  case "$*" in
    "config current-context")
      echo "arn:aws:eks:us-west-2:227896186585:cluster/o11y-dev-us-west-2-byoc-0303"
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if ! adoption_validate_cluster_context >/dev/null 2>&1; then
  echo "ERROR: Should pass with matching context" >&2
  exit 1
fi

echo "  ✓ Context validation passes for correct ARN"

kubectl() {
  case "$*" in
    "config current-context")
      echo "wrong-context"
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if adoption_validate_cluster_context >/dev/null 2>&1; then
  echo "ERROR: Should fail with non-matching context" >&2
  exit 1
fi

echo "  ✓ Context validation fails for wrong ARN"

# --- Test 3: adoption_compare_snapshots ---

echo "Test 3: adoption_compare_snapshots detects changes"

cat > "$tmpdir/before.txt" <<'EOF'
default|alertmanager-alert-regional-0|uid-am-0|Running|alertmanager:0
observability|regionalserver-0|uid-rs-0|Running|regionalserver:1
observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:3
EOF

cat > "$tmpdir/after.txt" <<'EOF'
default|alertmanager-alert-regional-0|uid-am-0|Running|alertmanager:0
observability|regionalserver-0|uid-rs-0|Running|regionalserver:1
observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:3
EOF

if ! adoption_compare_snapshots "$tmpdir/before.txt" "$tmpdir/after.txt" >/dev/null 2>&1; then
  echo "ERROR: Should pass for identical snapshots" >&2
  exit 1
fi

echo "  ✓ Identical snapshots pass comparison"

cat > "$tmpdir/after-restart.txt" <<'EOF'
default|alertmanager-alert-regional-0|uid-am-0|Running|alertmanager:1
observability|regionalserver-0|uid-rs-0|Running|regionalserver:1
observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:3
EOF

if adoption_compare_snapshots "$tmpdir/before.txt" "$tmpdir/after-restart.txt" >/dev/null 2>&1; then
  echo "ERROR: Should fail for changed restart count (alertmanager:0 -> alertmanager:1)" >&2
  exit 1
fi

echo "  ✓ Changed restart count detected"

cat > "$tmpdir/after-sidecar-restart.txt" <<'EOF'
default|alertmanager-alert-regional-0|uid-am-0|Running|alertmanager:0
observability|regionalserver-0|uid-rs-0|Running|regionalserver:1
observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:4
EOF

if adoption_compare_snapshots "$tmpdir/before.txt" "$tmpdir/after-sidecar-restart.txt" >/dev/null 2>&1; then
  echo "ERROR: Should fail for changed sidecar restart count (sidecar:3 -> sidecar:4)" >&2
  exit 1
fi

echo "  ✓ Sidecar restart count change detected"

cat > "$tmpdir/after-recreated.txt" <<'EOF'
default|alertmanager-alert-regional-0|uid-NEW|Running|alertmanager:0
observability|regionalserver-0|uid-rs-0|Running|regionalserver:1
observability|data-server-0|uid-ds-0|Running|data-server:0,sidecar:3
EOF

if adoption_compare_snapshots "$tmpdir/before.txt" "$tmpdir/after-recreated.txt" >/dev/null 2>&1; then
  echo "ERROR: Should fail for recreated pod (different UID)" >&2
  exit 1
fi

echo "  ✓ Pod recreation (UID change) detected"

# --- Test 4: adoption_verify_ops_server_health ---

echo "Test 4: adoption_verify_ops_server_health"

curl() {
  case "$*" in
    *"/health"*)
      return 0
      ;;
    *)
      echo "Unexpected curl call: $*" >&2
      return 1
      ;;
  esac
}
export -f curl

if ! adoption_verify_ops_server_health "http://localhost:8180" >/dev/null 2>&1; then
  echo "ERROR: Should pass when health endpoint returns success" >&2
  exit 1
fi

echo "  ✓ Health check passes when endpoint is healthy"

curl() {
  return 1
}
export -f curl

if adoption_verify_ops_server_health "http://localhost:8180" >/dev/null 2>&1; then
  echo "ERROR: Should fail when health endpoint fails" >&2
  exit 1
fi

echo "  ✓ Health check fails when endpoint is unhealthy"

# --- Test 5: adoption_wait_ops_server_ready ---

echo "Test 5: adoption_wait_ops_server_ready"

kubectl() {
  case "$*" in
    *"rollout status"*)
      return 0
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if ! adoption_wait_ops_server_ready "1s" >/dev/null 2>&1; then
  echo "ERROR: Should pass when rollout status succeeds" >&2
  exit 1
fi

echo "  ✓ Wait succeeds when deployment is ready"

kubectl() {
  case "$*" in
    *"rollout status"*)
      return 1
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if adoption_wait_ops_server_ready "1s" >/dev/null 2>&1; then
  echo "ERROR: Should fail when rollout status fails" >&2
  exit 1
fi

echo "  ✓ Wait fails when deployment is not ready"

# --- Test 6: adoption_verify_ops_server_helmrelease ---

echo "Test 6: adoption_verify_ops_server_helmrelease"

kubectl() {
  case "$*" in
    *"wait"*"helmrelease/ops-server"*)
      return 0
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if ! adoption_verify_ops_server_helmrelease "1s" >/dev/null 2>&1; then
  echo "ERROR: Should pass when HelmRelease wait succeeds" >&2
  exit 1
fi

echo "  ✓ HelmRelease verification passes when Ready"

kubectl() {
  case "$*" in
    *"wait"*"helmrelease/ops-server"*)
      return 1
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if adoption_verify_ops_server_helmrelease "1s" >/dev/null 2>&1; then
  echo "ERROR: Should fail when HelmRelease wait fails" >&2
  exit 1
fi

echo "  ✓ HelmRelease verification fails when not Ready"

# --- Test 7: adoption_adopt_alertmanager_regional with stubs ---

echo "Test 7: adoption_adopt_alertmanager_regional calls correct sequence"

# Set up test files
mkdir -p "$tmpdir/deployments/dataplane/alertmanager/envs/dev-aws-us-west-2-byoc-0303"
cat > "$tmpdir/deployments/dataplane/alertmanager/envs/dev-aws-us-west-2-byoc-0303/values.yaml" <<'YAML'
replicaCount: 2
YAML

mkdir -p "$tmpdir/deployments/charts/alertmanager"
cat > "$tmpdir/deployments/charts/alertmanager/Chart.yaml" <<'YAML'
apiVersion: v2
name: alertmanager-regional
version: 1.5.0
YAML

# Override REPO_ROOT for the test
REPO_ROOT="$tmpdir"

# Track function calls
call_log="$tmpdir/calls.log"
: > "$call_log"

read_chart_version() {
  echo "read_chart_version called: $*" >> "$call_log"
  echo "1.5.0"
}
export -f read_chart_version

create_or_update_helmrelease() {
  local server_url="$1"
  local name="$2"
  local namespace="$3"
  local component="$4"
  local values_file="$5"
  local version="$6"

  echo "create_or_update_helmrelease|server_url=$server_url|name=$name|namespace=$namespace|component=$component|values_file=$values_file|version=$version" >> "$call_log"
  return 0
}
export -f create_or_update_helmrelease

kubectl() {
  case "$*" in
    *"get helmrelease alertmanager-regional"*)
      echo "kubectl get helmrelease called" >> "$call_log"
      return 0
      ;;
    *"wait"*"helmrelease/alertmanager-regional"*)
      echo "kubectl wait helmrelease called" >> "$call_log"
      return 0
      ;;
    *)
      echo "Unexpected kubectl call: $*" >&2
      return 1
      ;;
  esac
}
export -f kubectl

if ! adoption_adopt_alertmanager_regional "http://ops-server:8180" "aws" "dev" "us-west-2-byoc-0303" >/dev/null 2>&1; then
  echo "ERROR: adoption_adopt_alertmanager_regional failed" >&2
  cat "$call_log" >&2
  exit 1
fi

# Verify the call sequence
if ! grep -q "read_chart_version" "$call_log"; then
  echo "ERROR: read_chart_version was not called" >&2
  cat "$call_log" >&2
  exit 1
fi

create_count="$(grep -c "create_or_update_helmrelease" "$call_log" || true)"
if [[ "$create_count" != "1" ]]; then
  echo "ERROR: Expected exactly one HelmRelease apply call, got $create_count" >&2
  cat "$call_log" >&2
  exit 1
fi

if ! grep -q "kubectl wait helmrelease called" "$call_log"; then
  echo "ERROR: kubectl wait for helmrelease was not called" >&2
  cat "$call_log" >&2
  exit 1
fi

echo "  ✓ adoption_adopt_alertmanager_regional calls a single unsuspended apply sequence"

echo ""
echo "All behavioral tests passed!"
