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

# Sourceable adoption functions for alertmanager-regional HelmRelease

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

# Only source lib.sh if not already sourced
if ! declare -f ops_api_url >/dev/null 2>&1; then
  source "${REPO_ROOT}/deployments/lib/lib.sh"
fi

# Default expected cluster ARN - can be overridden via EXPECTED_CLUSTER_ARN env var
DEFAULT_CLUSTER_ARN="arn:aws:eks:us-west-2:227896186585:cluster/o11y-dev-us-west-2-byoc-0303"

# Capture snapshot of monitored workloads covering alertmanager plus adjacent regional/dataplane workloads.
# Output format: namespace|pod-name|uid|phase|container:restartCount[,container:restartCount...]
adoption_capture_workload_snapshot() {
  local output_file="$1"
  : > "$output_file"
  
  # Alertmanager pods in default namespace (alertmanager-alert-regional-*)
  kubectl -n default get pods -o json 2>/dev/null | \
    jq -r '.items[] | select(.metadata.name | startswith("alertmanager-alert-regional-")) | 
      "default|\(.metadata.name)|\(.metadata.uid)|\(.status.phase)|\(
        [.status.containerStatuses[]? | "\(.name):\(.restartCount)"] | join(",")
      )"' \
    >> "$output_file" || true
  
  # Regional/dataplane workloads in observability namespace
  local observability_prefixes=(
    "regionalserver-"
    "data-server-"
    "loki-ha-backend-"
    "loki-ha-read-"
    "loki-ha-write-"
    "vmalert-vmalert-shared-"
    "vminsert-vmcluster-"
    "vmselect-vmcluster-"
    "vmstorage-vmcluster-"
  )
  
  for prefix in "${observability_prefixes[@]}"; do
    kubectl -n observability get pods -o json 2>/dev/null | \
      jq -r --arg prefix "$prefix" '.items[] | select(.metadata.name | startswith($prefix)) | 
        "observability|\(.metadata.name)|\(.metadata.uid)|\(.status.phase)|\(
          [.status.containerStatuses[]? | "\(.name):\(.restartCount)"] | join(",")
        )"' \
      >> "$output_file" || true
  done
}

# Validate cluster context matches expected ARN
adoption_validate_cluster_context() {
  local expected_arn="${1:-$DEFAULT_CLUSTER_ARN}"
  local current_context
  current_context="$(kubectl config current-context)"
  if [[ "$current_context" != "$expected_arn" ]]; then
    echo "ERROR: Current context '$current_context' does not match expected '$expected_arn'" >&2
    return 1
  fi
  echo "Context validated: $current_context"
  return 0
}

# Wait for ops-server deployment to be ready
adoption_wait_ops_server_ready() {
  local timeout="${1:-2m}"
  if ! kubectl -n ops-system rollout status deployment/ops-server --timeout="$timeout"; then
    echo "ERROR: ops-server deployment is not ready" >&2
    return 1
  fi
  return 0
}

# Verify ops-server health endpoint
adoption_verify_ops_server_health() {
  local ops_server_url="$1"
  local health_url="${ops_server_url%/}/health"
  if ! curl -fsS "$health_url" >/dev/null; then
    echo "ERROR: ops-server health check failed" >&2
    return 1
  fi
  echo "ops-server is healthy"
  return 0
}

# Verify ops-server HelmRelease is Ready
adoption_verify_ops_server_helmrelease() {
  local timeout="${1:-2m}"
  if ! kubectl -n ops-system wait --for=condition=Ready helmrelease/ops-server --timeout="$timeout"; then
    echo "ERROR: ops-server HelmRelease is not Ready" >&2
    return 1
  fi
  return 0
}

# Compare before/after snapshots and fail if workloads changed
adoption_compare_snapshots() {
  local before_file="$1"
  local after_file="$2"
  
  local before_snapshot after_snapshot
  before_snapshot="$(sort "$before_file")"
  after_snapshot="$(sort "$after_file")"
  
  if [[ "$before_snapshot" != "$after_snapshot" ]]; then
    echo "ERROR: Monitored workload pods changed during adoption!" >&2
    echo "" >&2
    echo "Before (sorted):" >&2
    echo "$before_snapshot" >&2
    echo "" >&2
    echo "After (sorted):" >&2
    echo "$after_snapshot" >&2
    echo "" >&2
    echo "Diff:" >&2
    diff <(echo "$before_snapshot") <(echo "$after_snapshot") || true
    return 1
  fi
  
  local pod_count
  pod_count="$(wc -l < "$before_file" | tr -d ' ')"
  echo "All monitored workload pods unchanged - adoption was non-disruptive ($pod_count pods verified)"
  return 0
}

# Adopt alertmanager-regional HelmRelease without suspending reconciliation.
adoption_adopt_alertmanager_regional() {
  local ops_server_url="$1"
  local vendor="${2:-aws}"
  local env="${3:-dev}"
  local logical_region="${4:-us-west-2-byoc-0303}"
  
  local am_values="${REPO_ROOT}/deployments/dataplane/alertmanager/envs/${env}-${vendor}-${logical_region}/values.yaml"
  if [[ ! -f "$am_values" ]]; then
    echo "ERROR: Alertmanager values file not found: $am_values" >&2
    return 1
  fi
  
  local charts_dir="${REPO_ROOT}/deployments/charts"
  local am_version
  am_version="$(read_chart_version "$charts_dir/alertmanager")"
  if [[ -z "$am_version" || "$am_version" == "null" ]]; then
    echo "ERROR: Failed to read alertmanager chart version" >&2
    return 1
  fi
  echo "Using alertmanager chart version: $am_version"
  
  echo "==> Applying HelmRelease 'alertmanager-regional'..."
  if ! create_or_update_helmrelease \
    "$ops_server_url" \
    "alertmanager-regional" \
    "default" \
    "alertmanager-regional" \
    "$am_values" \
    "$am_version"; then
    echo "ERROR: Failed to create/update HelmRelease for alertmanager-regional" >&2
    return 1
  fi
  
  echo "==> Waiting for HelmRelease 'alertmanager-regional' to become Ready..."
  if ! kubectl -n ops-system wait --for=condition=Ready helmrelease/alertmanager-regional --timeout=5m; then
    echo "ERROR: HelmRelease 'alertmanager-regional' did not become Ready within timeout" >&2
    echo "Current HelmRelease status:"
    kubectl -n ops-system get helmrelease alertmanager-regional -o yaml
    return 1
  fi
  
  return 0
}

# Main entry point when script is executed (not sourced)
adoption_main() {
  local expected_cluster_arn="${EXPECTED_CLUSTER_ARN:-$DEFAULT_CLUSTER_ARN}"
  local before_snapshot_file=""
  local after_snapshot_file=""
  
  # Single cleanup function for all resources
  cleanup_all() {
    if [[ -n "${before_snapshot_file:-}" ]]; then
      rm -f "$before_snapshot_file"
    fi
    if [[ -n "${after_snapshot_file:-}" ]]; then
      rm -f "$after_snapshot_file"
    fi
  }
  trap cleanup_all EXIT
  
  echo "==> Validating kubeconfig context..."
  adoption_validate_cluster_context "$expected_cluster_arn"
  
  echo "==> Checking ops-server rollout status..."
  adoption_wait_ops_server_ready "2m"
  
  if [[ -z "${OPS_SERVER_URL:-}" ]]; then
    local ops_server_values_file="${OPS_SERVER_VALUES_FILE:-${REPO_ROOT}/deployments/infra-v2/ops-server/envs/dev/regional-aws-us-west-2-byoc-0303.yaml}"
    if [[ ! -f "$ops_server_values_file" ]]; then
      echo "ERROR: ops-server values file not found: $ops_server_values_file" >&2
      exit 1
    fi
    OPS_SERVER_URL="$(resolve_ops_server_url "$ops_server_values_file")"
  fi
  if [[ -z "${OPS_SERVER_URL:-}" ]]; then
    echo "ERROR: OPS_SERVER_URL is not set and could not be resolved" >&2
    exit 1
  fi
  
  echo "==> Verifying ops-server health endpoint..."
  adoption_verify_ops_server_health "$OPS_SERVER_URL"
  
  echo "==> Verifying ops-server readiness via HelmRelease..."
  adoption_verify_ops_server_helmrelease "2m"
  
  echo "==> Capturing pre-adoption pod snapshot for monitored workloads..."
  echo "    (default: alertmanager-alert-regional-*, observability: regionalserver-*, data-server-*, loki-*, vm*)"
  before_snapshot_file="$(mktemp)"
  adoption_capture_workload_snapshot "$before_snapshot_file"
  
  if [[ ! -s "$before_snapshot_file" ]]; then
    echo "ERROR: Failed to capture any monitored workload pods" >&2
    echo "Expected to find pods in:" >&2
    echo "  - namespace 'default': alertmanager-alert-regional-*" >&2
    echo "  - namespace 'observability': regionalserver-*, data-server-*, loki-ha-*, vmalert-*, vminsert-*, vmselect-*, vmstorage-*" >&2
    exit 1
  fi
  
  local pod_count
  pod_count="$(wc -l < "$before_snapshot_file" | tr -d ' ')"
  echo "Pre-adoption snapshot captured ($pod_count pods):"
  cat "$before_snapshot_file"
  
  adoption_adopt_alertmanager_regional "$OPS_SERVER_URL" "aws" "dev" "us-west-2-byoc-0303"
  
  echo "==> Verifying monitored workload pods did not restart or get recreated..."
  after_snapshot_file="$(mktemp)"
  adoption_capture_workload_snapshot "$after_snapshot_file"
  adoption_compare_snapshots "$before_snapshot_file" "$after_snapshot_file"
  
  echo ""
  echo "==> Adoption complete!"
  echo "HelmRelease 'alertmanager-regional' is now managed by ops-server in namespace 'ops-system'"
}

# Execute main only if script is run directly (not sourced)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  adoption_main "$@"
fi
