#!/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 "$REPO_ROOT/deployments/lib/lib.sh"

DEFAULT_CLUSTER_ARN="arn:aws:eks:us-west-2:227896186585:cluster/o11y-dev-us-west-2-byoc-0303"
DEFAULT_AWS_PROFILE="227896186585"
DEFAULT_AWS_REGION="us-west-2"
DEFAULT_REST_API_ID="3tq68nh3nf"
DEFAULT_REGION_ID="aws-us-west-2"
DEFAULT_LOGICAL_REGION="us-west-2-byoc-0303"
DEFAULT_REGIONAL_LB_NAME="alb-rs-us-west-2-byoc-0303"

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "ERROR: missing command: $1" >&2; return 1; }
}

validate_live_env() {
  : "${O11Y_OPS_API_BASE_URL:?O11Y_OPS_API_BASE_URL is required}"
  if [[ -z "${O11Y_OPS_API_TOKEN:-}" && -z "${OPS_API_ACCESS_TOKEN:-}" ]]; then
    : "${AUTH0_CLIENT_ID:?AUTH0_CLIENT_ID is required when O11Y_OPS_API_TOKEN is unset}"
    : "${AUTH0_CLIENT_SECRET:?AUTH0_CLIENT_SECRET is required when O11Y_OPS_API_TOKEN is unset}"
  fi
}

validate_kube_context() {
  local expected="${1:-$DEFAULT_CLUSTER_ARN}"
  local current
  current="$(kubectl config current-context)"
  [[ "$current" == "$expected" ]] || { echo "ERROR: current kubecontext is $current, expected $expected" >&2; return 1; }
}

validate_aws_account() {
  local profile="${1:-$DEFAULT_AWS_PROFILE}"
  local account
  account="$(AWS_PAGER= aws --profile "$profile" sts get-caller-identity --query Account --output text)"
  [[ "$account" == "227896186585" ]] || { echo "ERROR: AWS profile $profile resolved to account $account" >&2; return 1; }
}

validate_api_gateway_ops_path() {
  local profile="${1:-$DEFAULT_AWS_PROFILE}"
  local region="${2:-$DEFAULT_AWS_REGION}"
  local rest_api_id="${3:-$DEFAULT_REST_API_ID}"
  if ! AWS_PAGER= aws --profile "$profile" --region "$region" apigateway get-resources \
    --rest-api-id "$rest_api_id" \
    --query 'items[?path==`/rs/{proxy+}`].{id:id,path:path,methods:resourceMethods}' \
    --output json | jq -e '
      length > 0 and
      any(.[]; .path == "/rs/{proxy+}" and (.methods.ANY != null))
    ' >/dev/null; then
    echo "ERROR: REST API $rest_api_id is missing /rs/{proxy+} with ANY method" >&2
    return 1
  fi
}

validate_regional_alb_target() {
  local profile="${1:-$DEFAULT_AWS_PROFILE}"
  local region="${2:-$DEFAULT_AWS_REGION}"
  local lb_name="${3:-$DEFAULT_REGIONAL_LB_NAME}"
  local lb_arn tg_arn

  lb_arn="$(AWS_PAGER= aws --profile "$profile" --region "$region" elbv2 describe-load-balancers \
    --names "$lb_name" --query 'LoadBalancers[0].LoadBalancerArn' --output text)"
  [[ -n "$lb_arn" && "$lb_arn" != "None" ]] || { echo "ERROR: load balancer $lb_name not found" >&2; return 1; }

  tg_arn="$(AWS_PAGER= aws --profile "$profile" --region "$region" elbv2 describe-target-groups \
    --load-balancer-arn "$lb_arn" --query 'TargetGroups[0].TargetGroupArn' --output text)"
  [[ -n "$tg_arn" && "$tg_arn" != "None" ]] || { echo "ERROR: no target group found for load balancer $lb_name ($lb_arn)" >&2; return 1; }

  if ! AWS_PAGER= aws --profile "$profile" --region "$region" elbv2 describe-target-health \
    --target-group-arn "$tg_arn" \
    --query 'TargetHealthDescriptions[].TargetHealth.State' --output text | tr '\t' '\n' | grep -q '^healthy$'; then
    echo "ERROR: no healthy target in target group $tg_arn for load balancer $lb_name" >&2
    return 1
  fi
}

global_ops_api_get() {
  local path="$1"
  local region_id="${O11Y_OPS_API_REGION_ID:-$DEFAULT_REGION_ID}"
  local logical_region="${O11Y_OPS_API_LOGICAL_REGION:-$DEFAULT_LOGICAL_REGION}"
  local headers_json

  if [[ -z "${OPS_API_ACCESS_TOKEN:-}" && -n "${O11Y_OPS_API_TOKEN:-}" ]]; then
    OPS_API_ACCESS_TOKEN="$O11Y_OPS_API_TOKEN"
  fi

  mint_ops_api_token >/dev/null
  headers_json="$(build_ops_api_headers "$OPS_API_ACCESS_TOKEN" "$region_id" "$logical_region")"
  ops_api_request GET "$O11Y_OPS_API_BASE_URL" "$path" "$headers_json"
}

main() {
  local response

  validate_live_env
  require_cmd aws
  require_cmd curl
  require_cmd jq
  require_cmd kubectl
  validate_kube_context "${EXPECTED_CLUSTER_ARN:-$DEFAULT_CLUSTER_ARN}"
  validate_aws_account "${AWS_PROFILE:-$DEFAULT_AWS_PROFILE}"
  validate_api_gateway_ops_path "${AWS_PROFILE:-$DEFAULT_AWS_PROFILE}" "${AWS_REGION:-$DEFAULT_AWS_REGION}" "${REST_API_ID:-$DEFAULT_REST_API_ID}"
  validate_regional_alb_target "${AWS_PROFILE:-$DEFAULT_AWS_PROFILE}" "${AWS_REGION:-$DEFAULT_AWS_REGION}" "${REGIONAL_LB_NAME:-$DEFAULT_REGIONAL_LB_NAME}"

  response="$(global_ops_api_get "helmreleases")"
  if ! echo "$response" | jq -e '.data.helmReleases | type == "array"' >/dev/null; then
    echo "ERROR: global ops API did not return a HelmRelease list response" >&2
    return 1
  fi
  echo "$response" | jq .
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
