#!/usr/bin/env bash
# Axiom API helper - reads credentials from ~/.axiom.toml
# Usage: axiom-api <deployment> <method> <endpoint> [body]
# Examples:
#   axiom-api dev POST "/v1/datasets/_apl?format=tabular" '{"apl": "..."}'
#   axiom-api dev GET "/v1/datasets"

set -euo pipefail

DEPLOYMENT="${1:-}"
METHOD="${2:-GET}"
ENDPOINT="${3:-}"
BODY="${4:-}"

if [[ -z "$DEPLOYMENT" || -z "$ENDPOINT" ]]; then
  echo "Usage: axiom-api <deployment> <method> <endpoint> [body]" >&2
  exit 1
fi

CONFIG_FILE="$HOME/.axiom.toml"
if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "Error: $CONFIG_FILE not found" >&2
  exit 1
fi

# Parse TOML for deployment config (simple parser for known structure)
extract_value() {
  local key="$1"
  awk -v deployment="$DEPLOYMENT" -v key="$key" '
    /^\[deployments\./ { in_deployment = ($0 ~ "\\[deployments\\." deployment "\\]") }
    in_deployment && $1 == key { gsub(/[" ]/, "", $3); print $3; exit }
  ' "$CONFIG_FILE"
}

URL=$(extract_value "url")
TOKEN=$(extract_value "token")
ORG_ID=$(extract_value "org_id")

if [[ -z "$URL" || -z "$TOKEN" || -z "$ORG_ID" ]]; then
  echo "Error: Could not find deployment '$DEPLOYMENT' in $CONFIG_FILE" >&2
  exit 1
fi

# Build curl command
CURL_ARGS=(
  -s
  -X "$METHOD"
  "${URL}${ENDPOINT}"
  -H "Authorization: Bearer $TOKEN"
  -H "X-Axiom-Org-Id: $ORG_ID"
  -H "Content-Type: application/json"
)

if [[ -n "$BODY" ]]; then
  CURL_ARGS+=(-d "$BODY")
fi

curl "${CURL_ARGS[@]}"
