#!/usr/bin/env bash
# Adaptive two-level Google Places sweep:
#   Level 1 — query all 50 states (50 queries)
#   Level 2 — for states that hit the 60-result cap, re-query by major city
#
# Usage:
#   ./google-places-adaptive.sh "hindu temples"
#   ./google-places-adaptive.sh "indian restaurants" --key YOUR_API_KEY
#   ./google-places-adaptive.sh "hindu temples" --refresh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLACES="$SCRIPT_DIR/google-places.sh"
DATA_DIR="$SCRIPT_DIR/../data/google_places"
CITIES_FILE="$SCRIPT_DIR/../data/us_cities_by_state.json"

TERM=""
PASSTHROUGH_ARGS=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    --key)     PASSTHROUGH_ARGS+=(--key "$2"); shift 2 ;;
    --refresh) PASSTHROUGH_ARGS+=(--refresh); shift ;;
    *)         TERM="$1"; shift ;;
  esac
done

if [[ -z "$TERM" ]]; then
  echo "Usage: $0 \"<search term>\" [--key API_KEY] [--refresh]"
  exit 1
fi

STATES=(
  "Alabama" "Alaska" "Arizona" "Arkansas" "California"
  "Colorado" "Connecticut" "Delaware" "Florida" "Georgia"
  "Hawaii" "Idaho" "Illinois" "Indiana" "Iowa"
  "Kansas" "Kentucky" "Louisiana" "Maine" "Maryland"
  "Massachusetts" "Michigan" "Minnesota" "Mississippi" "Missouri"
  "Montana" "Nebraska" "Nevada" "New Hampshire" "New Jersey"
  "New Mexico" "New York" "North Carolina" "North Dakota" "Ohio"
  "Oklahoma" "Oregon" "Pennsylvania" "Rhode Island" "South Carolina"
  "South Dakota" "Tennessee" "Texas" "Utah" "Vermont"
  "Virginia" "Washington" "West Virginia" "Wisconsin" "Wyoming"
)

SLUG=$(echo "$TERM" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9 ]//g' | tr ' ' '_' | sed 's/__*/_/g')

echo "=== Google Places Adaptive Sweep ==="
echo "Term: \"$TERM\""
echo ""

# ── Level 1: states ──────────────────────────────────────────────────────────
echo "── Level 1: States ──"
CAPPED_STATES=()

for state in "${STATES[@]}"; do
  STATE_SLUG=$(echo "$state" | tr '[:upper:]' '[:lower:]' | tr ' ' '_')
  RESULT_FILE="$DATA_DIR/${SLUG}_in_${STATE_SLUG}/all_places.json"

  "$PLACES" "$TERM in $state" ${PASSTHROUGH_ARGS[@]+"${PASSTHROUGH_ARGS[@]}"} || true

  COUNT=$(jq 'length' "$RESULT_FILE" 2>/dev/null || echo 0)
  if [[ "$COUNT" -ge 60 ]]; then
    CAPPED_STATES+=("$state")
    echo "  ⚠ $state hit cap ($COUNT results) — will drill into cities"
  else
    echo "  ✓ $state complete ($COUNT results)"
  fi
done

echo ""

# ── Level 2: cities for capped states ────────────────────────────────────────
if [[ ${#CAPPED_STATES[@]} -eq 0 ]]; then
  echo "── No states hit the cap — sweep complete!"
else
  echo "── Level 2: Cities for ${#CAPPED_STATES[@]} capped state(s) ──"
  echo ""

  for state in "${CAPPED_STATES[@]}"; do
    echo "── $state ──"
    CITIES=$(jq -r --arg s "$state" '.[$s] // [] | .[]' "$CITIES_FILE")

    if [[ -z "$CITIES" ]]; then
      echo "  No city list found for $state — skipping"
      continue
    fi

    while IFS= read -r city; do
      "$PLACES" "$TERM in $city, $state" ${PASSTHROUGH_ARGS[@]+"${PASSTHROUGH_ARGS[@]}"} || true
    done <<< "$CITIES"
    echo ""
  done
fi

# ── Summary ───────────────────────────────────────────────────────────────────
echo "=== Done ==="
echo ""
echo "Results saved to: $DATA_DIR/${SLUG}_in_*/"
echo ""
echo "To see total unique results across all files:"
echo "  jq -s '[.[]|.[]]|unique_by(.id)|length' $DATA_DIR/${SLUG}_in_*/all_places.json"
