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

BASE_URL="${APIDATASETS_BASE_URL:-https://apidatasets.com}"
INSTALL_DIR="${APIDATASETS_INSTALL_DIR:-$HOME/.local/bin}"
BIN="$INSTALL_DIR/apidatasets"

if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required to use the ApiDatasets CLI." >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"

cat > "$BIN" <<'APIDATASETS_CLI'
#!/usr/bin/env bash
set -euo pipefail

ROOT="${APIDATASETS_BASE_URL:-https://apidatasets.com}"
ROOT="${ROOT%/}"
if [ "${ROOT%/api/v1}" != "$ROOT" ]; then
  SITE_ROOT="${ROOT%/api/v1}"
  API_ROOT="$ROOT"
else
  SITE_ROOT="$ROOT"
  API_ROOT="$SITE_ROOT/api/v1"
fi
DEMO_ROOT="$SITE_ROOT/demo/api/v1"

pretty_json() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -m json.tool
  else
    cat
  fi
}

urlencode() {
  if command -v python3 >/dev/null 2>&1; then
    python3 - "$1" <<'PY'
import sys
import urllib.parse

print(urllib.parse.quote(sys.argv[1], safe=""))
PY
  else
    printf '%s' "$1"
  fi
}

usage() {
  cat <<'HELP'
ApiDatasets CLI

Usage:
  apidatasets demo geo [30301|30303|10001|94105]
  apidatasets demo tax [single|married_filing_jointly|head_of_household]
  apidatasets demo company [example.com|apple.com|microsoft.com]
  apidatasets demo jobs [python|cloud]
  apidatasets call /geo/zip/30301
  apidatasets init
  apidatasets open

Demo commands use guarded, no-key endpoints. Production calls require:
  export APIDATASETS_API_KEY=ad_live_...

The CLI is optional. ApiDatasets also works with standard HTTPS requests:
  curl https://apidatasets.com/api/v1/geo/zip/30301 -H "Authorization: Bearer YOUR_API_KEY"
HELP
}

demo_get() {
  curl -sS "$DEMO_ROOT$1" | pretty_json
}

demo_command() {
  dataset="${1:-geo}"
  case "$dataset" in
    geo)
      zip="${2:-30301}"
      demo_get "/geo/zip/$zip"
      ;;
    tax)
      status="${2:-single}"
      demo_get "/tax/federal/brackets?year=2026&filing_status=$status"
      ;;
    company)
      domain="${2:-example.com}"
      encoded="$(urlencode "$domain")"
      demo_get "/company/domain?domain=$encoded"
      ;;
    jobs)
      skill="${2:-python}"
      encoded="$(urlencode "$skill")"
      demo_get "/jobs/trends?skill=$encoded"
      ;;
    flight|flights)
      origin="${2:-ATL}"
      dest="${3:-LGA}"
      demo_get "/flights/reliability?origin=$origin&dest=$dest"
      ;;
    *)
      echo "Unknown demo dataset: $dataset" >&2
      usage
      exit 2
      ;;
  esac
}

production_call() {
  path="${1:-}"
  if [ -z "$path" ]; then
    echo "Pass a production API path, for example: apidatasets call /geo/zip/30301" >&2
    exit 2
  fi
  if [ -z "${APIDATASETS_API_KEY:-}" ]; then
    cat >&2 <<'MSG'
APIDATASETS_API_KEY is not set.

Create a free key at https://apidatasets.com/dashboard/api-keys, then run:
  export APIDATASETS_API_KEY=ad_live_...
  apidatasets call /geo/zip/30301

For no-key testing, use:
  apidatasets demo geo 30301
MSG
    exit 2
  fi

  case "$path" in
    http://*|https://*) url="$path" ;;
    /api/v1/*) url="$SITE_ROOT$path" ;;
    api/v1/*) url="$SITE_ROOT/$path" ;;
    /*) url="$API_ROOT$path" ;;
    *) url="$API_ROOT/$path" ;;
  esac

  curl -sS -H "Authorization: Bearer $APIDATASETS_API_KEY" "$url" | pretty_json
}

init_project() {
  env_file=".env.local"
  if [ -f "$env_file" ] && grep -q '^APIDATASETS_API_KEY=' "$env_file"; then
    echo "$env_file already contains APIDATASETS_API_KEY."
    echo "Run: source $env_file"
    return
  fi

  cat > "$env_file" <<ENV
APIDATASETS_BASE_URL=$SITE_ROOT
APIDATASETS_API_KEY=replace_me_with_your_key
ENV
  cat <<MSG
Created $env_file.

Next:
  1. Get a key: $SITE_ROOT/dashboard/api-keys
  2. Edit $env_file and replace the placeholder key.
  3. Run: source $env_file
  4. Run: apidatasets call /geo/zip/30301
MSG
}

open_dashboard() {
  url="$SITE_ROOT/dashboard/api-keys"
  if command -v open >/dev/null 2>&1; then
    open "$url"
  elif command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$url"
  else
    echo "$url"
  fi
}

case "${1:-help}" in
  help|-h|--help)
    usage
    ;;
  version|--version)
    echo "apidatasets 0.1.0"
    ;;
  demo)
    shift
    demo_command "$@"
    ;;
  call|get)
    shift
    production_call "$@"
    ;;
  init)
    init_project
    ;;
  open|keys)
    open_dashboard
    ;;
  *)
    echo "Unknown command: $1" >&2
    usage
    exit 2
    ;;
esac
APIDATASETS_CLI

chmod +x "$BIN"

echo "Installed apidatasets to $BIN"
if ! command -v apidatasets >/dev/null 2>&1; then
  echo "Add this to your shell profile if apidatasets is not on your PATH:"
  echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
fi
echo
echo "Try a guarded no-key demo:"
echo "  apidatasets demo geo 30301"
echo
echo "Then connect a production API key:"
echo "  apidatasets init"
