#!/usr/bin/env bash
# Fetches all Telugu movies from TMDB discover API, one JSON file per page.
# Stores pages in data/tmdb_te_movies/ for reuse.
#
# Usage: ./tmdb-te-movies.sh [--refresh]
#   --refresh  Re-fetch even if cached pages exist

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OUT_DIR="$SCRIPT_DIR/../data/tmdb_te_movies"
API_KEY="bcab21ebfee42b8f801ff52912a30191"
BASE_URL="https://api.themoviedb.org/3/discover/movie"
PARAMS="api_key=$API_KEY&with_original_language=te&sort_by=primary_release_date.desc"
REFRESH=false

for arg in "$@"; do
  [[ "$arg" == "--refresh" ]] && REFRESH=true
done

mkdir -p "$OUT_DIR"

# Fetch a single page and return parsed JSON
fetch_page() {
  local page=$1
  curl -sf "$BASE_URL?$PARAMS&page=$page"
}

echo "=== TMDB Telugu Movies pipeline ==="

# Page 1 to get total_pages
PAGE1_FILE="$OUT_DIR/page_001.json"
if [[ "$REFRESH" == true || ! -f "$PAGE1_FILE" ]]; then
  echo "Fetching page 1..."
  fetch_page 1 > "$PAGE1_FILE"
fi

TOTAL_PAGES=$(jq '.total_pages' "$PAGE1_FILE")
TOTAL_RESULTS=$(jq '.total_results' "$PAGE1_FILE")
echo "Total results: $TOTAL_RESULTS across $TOTAL_PAGES pages"

# Fetch remaining pages
for ((page=2; page<=TOTAL_PAGES; page++)); do
  FILE="$OUT_DIR/$(printf 'page_%03d.json' "$page")"
  if [[ "$REFRESH" == false && -f "$FILE" ]]; then
    echo "  page $page — cached, skipping"
    continue
  fi
  echo "  Fetching page $page / $TOTAL_PAGES..."
  fetch_page "$page" > "$FILE"
  sleep 0.25  # be polite to the API
done

# Merge all pages and add full image URLs
echo ""
echo "Merging all pages → $OUT_DIR/all_movies.json"
jq -s '[.[].results[] | . + {
  poster_url:   (if .poster_path   then "https://image.tmdb.org/t/p/w500\(.poster_path)"   else null end),
  backdrop_url: (if .backdrop_path then "https://image.tmdb.org/t/p/w1280\(.backdrop_path)" else null end)
}]' "$OUT_DIR"/page_*.json > "$OUT_DIR/all_movies.json"
TOTAL=$(jq 'length' "$OUT_DIR/all_movies.json")
echo "Done — $TOTAL movies saved to $OUT_DIR/all_movies.json"
