#!/usr/bin/env bash
# Fetches Google Places data for a query across all US counties.
# Each county gets its own all_places.json under data/google_places/<slug>_in_<county>/
#
# Usage:
#   ./google-places-counties.sh "hindu temples"
#   ./google-places-counties.sh "indian restaurants" --states "Texas,California"
#   ./google-places-counties.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"
COUNTIES_FILE="$SCRIPT_DIR/../data/us_counties.csv"

TERM=""
PASSTHROUGH_ARGS=()
FILTER_STATES=""

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

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

# Download county list from Census Bureau if not cached
if [[ ! -f "$COUNTIES_FILE" ]]; then
  echo "Downloading US county list..."
  curl -sf "https://raw.githubusercontent.com/kjhealy/fips-codes/master/state_and_county_fips_master.csv" \
    > "$COUNTIES_FILE"
  echo "Saved → $COUNTIES_FILE"
  echo ""
fi

echo "=== Google Places — all US counties ==="
echo "Term: $TERM"
[[ -n "$FILTER_STATES" ]] && echo "States: $FILTER_STATES"
echo ""

# Parse CSV: columns are fips, name, state
# Skip header, skip state-level rows (county name is just the state name)
while IFS=',' read -r fips name state; do
  [[ "$fips" == "fips" ]] && continue         # header
  [[ -z "$name" || -z "$state" ]] && continue  # blank
  [[ "$name" == "$state" ]] && continue         # state-level row

  # Strip surrounding quotes
  name="${name//\"/}"
  state="${state//\"/}"

  # Filter by state if --states passed
  if [[ -n "$FILTER_STATES" ]]; then
    match=false
    IFS=',' read -ra WANTED <<< "$FILTER_STATES"
    for w in "${WANTED[@]}"; do
      [[ "${state,,}" == "${w,,}" ]] && match=true && break
    done
    [[ "$match" == false ]] && continue
  fi

  QUERY="$TERM in $name, $state"
  echo "--- $name, $state ---"
  "$PLACES" "$QUERY" "${PASSTHROUGH_ARGS[@]}" || true
  echo ""

done < "$COUNTIES_FILE"

echo "=== Done — results saved to $DATA_DIR/ ==="
