#!/usr/bin/env bash
# tidbcloud-auth.sh - Load credentials and provide digest auth for TiDB Cloud API.
#
# Usage:
#   source scripts/tidbcloud-auth.sh
#   load_tidbcloud_auth [--sut tidbx|tidbx-premium]
#
# After sourcing, the following variables are exported:
#   TIDBCLOUD_API_HOST        - API host (e.g. serverless.tidbapi.com)
#   TIDBCLOUD_API_BASE_PATH   - Base path (e.g. /v1beta1)
#   TIDBCLOUD_API_BASE_URL    - Full base URL (https://host/base_path)
#   _TIDBCLOUD_PUBLIC_KEY     - (internal) public key for digest auth
#   _TIDBCLOUD_PRIVATE_KEY    - (internal) private key for digest auth
#
# Functions:
#   tidbcloud_curl [curl_args...]  - curl wrapper with digest auth injected

set -euo pipefail

# Resolve the skill root directory (where SKILL.md lives)
_resolve_skill_root() {
  local dir
  # If TIDBCLOUD_SKILL_DIR is set, use it
  if [[ -n "${TIDBCLOUD_SKILL_DIR:-}" ]]; then
    echo "$TIDBCLOUD_SKILL_DIR"
    return
  fi
  # Walk up from this script's location to find SKILL.md
  dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
  if [[ -f "$dir/SKILL.md" ]]; then
    echo "$dir"
    return
  fi
  # Fallback: current directory
  if [[ -f "./SKILL.md" ]]; then
    pwd
    return
  fi
  echo >&2 "ERROR: Cannot locate skill root (no SKILL.md found). Set TIDBCLOUD_SKILL_DIR."
  return 1
}

# Load .env file if present (simple key=value parser, no dependencies)
_load_dotenv() {
  local env_file="$1"
  [[ -f "$env_file" ]] || return 0
  while IFS= read -r line || [[ -n "$line" ]]; do
    # Skip comments and blank lines
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    [[ -z "${line// /}" ]] && continue
    # Only export if not already set (override=false behavior)
    local key="${line%%=*}"
    key="${key// /}"
    if [[ -z "${!key:-}" ]]; then
      local val="${line#*=}"
      # Strip surrounding quotes
      val="${val#\"}"
      val="${val%\"}"
      val="${val#\'}"
      val="${val%\'}"
      export "$key=$val"
    fi
  done < "$env_file"
}

# Main loader: resolve SUT and set auth variables
# Usage: load_tidbcloud_auth [--sut tidbx|tidbx-premium]
load_tidbcloud_auth() {
  local sut="tidbx"
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --sut) sut="$2"; shift 2 ;;
      *) shift ;;
    esac
  done

  # Normalize SUT aliases
  case "$sut" in
    premium|tidbx_premium|tidbcloud_premium) sut="tidbx-premium" ;;
    tidbx|tidbcloud_serverless|"") sut="tidbx" ;;
  esac

  local skill_root
  skill_root="$(_resolve_skill_root)"

  # Load .env from skill root
  _load_dotenv "$skill_root/.env"

  # Read connection config from sut.yaml (using simple grep/sed, no yq dependency)
  local sut_yaml="$skill_root/configs/$sut/sut.yaml"
  if [[ ! -f "$sut_yaml" ]]; then
    echo >&2 "ERROR: SUT config not found: $sut_yaml"
    return 1
  fi

  # Resolve host and base_path based on SUT
  case "$sut" in
    tidbx)
      TIDBCLOUD_API_HOST="${TIDBCLOUD_HOST:-serverless.tidbapi.com}"
      TIDBCLOUD_API_BASE_PATH="${TIDBCLOUD_BASE_PATH:-/v1beta1}"
      ;;
    tidbx-premium)
      TIDBCLOUD_API_HOST="${TIDBCLOUD_PREMIUM_HOST:-cloud.tidbapi.com}"
      TIDBCLOUD_API_BASE_PATH="${TIDBCLOUD_PREMIUM_BASE_PATH:-/v1beta2}"
      ;;
    *)
      echo >&2 "ERROR: Unknown SUT: $sut"
      return 1
      ;;
  esac

  TIDBCLOUD_API_BASE_URL="https://${TIDBCLOUD_API_HOST}${TIDBCLOUD_API_BASE_PATH}"
  export TIDBCLOUD_API_HOST TIDBCLOUD_API_BASE_PATH TIDBCLOUD_API_BASE_URL

  # Load credentials
  _TIDBCLOUD_PUBLIC_KEY="${TIDB_PUBLIC_KEY:-}"
  _TIDBCLOUD_PRIVATE_KEY="${TIDB_PRIVATE_KEY:-}"

  if [[ -z "$_TIDBCLOUD_PUBLIC_KEY" || -z "$_TIDBCLOUD_PRIVATE_KEY" ]]; then
    # Try credential file fallback
    local cred_file="${HOME}/.tidb-credentials.json"
    if [[ -f "$cred_file" ]]; then
      _TIDBCLOUD_PUBLIC_KEY="$(jq -r '.public_key // empty' "$cred_file" 2>/dev/null || true)"
      _TIDBCLOUD_PRIVATE_KEY="$(jq -r '.private_key // empty' "$cred_file" 2>/dev/null || true)"
    fi
  fi

  if [[ -z "$_TIDBCLOUD_PUBLIC_KEY" || -z "$_TIDBCLOUD_PRIVATE_KEY" ]]; then
    echo >&2 "ERROR: Missing credentials. Set TIDB_PUBLIC_KEY and TIDB_PRIVATE_KEY in .env or environment."
    return 1
  fi

  export _TIDBCLOUD_PUBLIC_KEY _TIDBCLOUD_PRIVATE_KEY
  export TIDBCLOUD_CURRENT_SUT="$sut"
}

# curl wrapper with digest auth. Never prints credentials.
# Usage: tidbcloud_curl [curl_args...]
# Example: tidbcloud_curl -s -X GET "${TIDBCLOUD_API_BASE_URL}/clusters"
tidbcloud_curl() {
  if [[ -z "${_TIDBCLOUD_PUBLIC_KEY:-}" || -z "${_TIDBCLOUD_PRIVATE_KEY:-}" ]]; then
    echo >&2 "ERROR: Auth not loaded. Run load_tidbcloud_auth first."
    return 1
  fi
  curl --digest \
    -u "${_TIDBCLOUD_PUBLIC_KEY}:${_TIDBCLOUD_PRIVATE_KEY}" \
    "$@"
}
