#!/bin/bash
# Sync tafsir book JSON filenames with versions from API

API_URL="https://v2.goldenquran.org/api/v2/quraan/books"
DIR="${1:-.}"
cd "$DIR" || { echo "❌ Directory not found"; exit 1; }

echo "📡 Fetching book data from API..."
data=$(curl -s --location "$API_URL" --header 'Accept: application/json')

if [[ -z "$data" ]]; then
  echo "❌ Failed to fetch data from API"
  exit 1
fi

if ! command -v jq >/dev/null; then
  echo "❌ 'jq' is required (install via 'apt install jq')"
  exit 1
fi

echo "✅ Data fetched. Parsing..."
echo

# Extract each tafsir book entry from JSON
echo "$data" | jq -c '.data.tafser_books[]' | while read -r book; do
  id=$(echo "$book" | jq -r '.id')
  version=$(echo "$book" | jq -r '.version')

  # Skip invalid entries
  if [[ "$id" == "null" || "$version" == "null" ]]; then
    continue
  fi

  # Find local file for this ID
  old_file=$(ls "${id}_v"*.json 2>/dev/null | head -n 1)

  if [[ -n "$old_file" ]]; then
    new_file="${id}_v${version}.json"

    if [[ "$old_file" != "$new_file" ]]; then
      echo "🔄 Renaming: $old_file → $new_file"
      mv -f "$old_file" "$new_file"
    else
      echo "✅ Already correct: $new_file"
    fi
  else
    echo "⚠️ No local file found for ID: $id"
  fi
done

echo
echo "🎯 Done syncing file names with API versions."
