#!/usr/bin/env bash
# TPDB import helper (TUI-friendly runner)
# Usage:
#   ./scripts/tpdb_import.sh all
#   ./scripts/tpdb_import.sh performers
#   ./scripts/tpdb_import.sh studios
#   ./scripts/tpdb_import.sh scenes

set -euo pipefail

cmd="${1:-}"

# Try env first, then config/api_keys.json
if [[ -z "${TPDB_API_KEY:-}" ]]; then
  if [[ -f "../config/api_keys.json" ]]; then
    TPDB_API_KEY="$(
python - <<'PY' "../config/api_keys.json"
import json, sys
p = sys.argv[1]
try:
    with open(p) as f:
        data = json.load(f)
    print(data.get("tpdb_api_key", ""))
except Exception:
    print("")
PY
    )"
  fi
fi

if [[ -z "${TPDB_API_KEY:-}" ]]; then
  echo "TPDB_API_KEY is not set. Export it, or save it via scripts/set_api_key.sh." >&2
  echo '  export TPDB_API_KEY="your-key-here"' >&2
  exit 1
fi

run() {
  echo "▶ $*"
  repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
  if [[ -x "$repo_root/goondex" ]]; then
    exec "$repo_root/goondex" "$@"
  elif [[ -x "$repo_root/bin/goondex" ]]; then
    exec "$repo_root/bin/goondex" "$@"
  else
    echo "goondex binary not found. Build it first with: go build -o bin/goondex ./cmd/goondex" >&2
    exit 1
  fi
}

case "$cmd" in
  all)
    run import all
    ;;
  performers|performer)
    run import performer
    ;;
  studios|studio)
    run import studio
    ;;
  scenes|scene)
    run import scene
    ;;
  *)
    cat <<'EOF' >&2
Usage: ./scripts/tpdb_import.sh {all|performers|studios|scenes}

Examples:
  ./scripts/tpdb_import.sh all
  ./scripts/tpdb_import.sh performers
  ./scripts/tpdb_import.sh studios
  ./scripts/tpdb_import.sh scenes
EOF
    exit 1
    ;;
esac
