#!/usr/bin/env bash
# warm-tile-cache.sh — Pre-populate nginx tile cache with common tiles
# Usage: ./scripts/warm-tile-cache.sh [BASE_URL]
# Run after deploy or cache purge to ensure fast first-load for users.

set -euo pipefail

BASE="${1:-http://10.10.10.166:3010}"
PARALLEL="${PARALLEL:-8}"
TOTAL=0
HITS=0

echo "[$(date -Iseconds)] Warming tile cache at $BASE ..."

# ── Helper: fetch a range of tiles ──
fetch_tiles() {
  local source="$1" z="$2" x_min="$3" x_max="$4" y_min="$5" y_max="$6"
  for x in $(seq "$x_min" "$x_max"); do
    for y in $(seq "$y_min" "$y_max"); do
      echo "${BASE}/${source}/${z}/${x}/${y}"
    done
  done
}

# ── Romania bounding box at various zoom levels ──
# Lon: 20.2-30.0, Lat: 43.5-48.3
# Tile coords computed from slippy map formula

# z5: UATs coarse (2 tiles)
fetch_tiles gis_uats_z5 5 17 18 11 11

# z7: UATs moderate (12 tiles)
fetch_tiles gis_uats_z8 7 69 73 44 46

# z8: UATs + labels (40 tiles)
fetch_tiles gis_uats_z8 8 139 147 88 92

# z9: UATs labels (100 tiles — major cities area)
fetch_tiles gis_uats_z8 9 279 288 177 185

# z10: Administrativ + terenuri sources start loading
# Focus on major metro areas: Bucharest, Cluj, Timisoara, Iasi, Brasov
# Bucharest area (z12)
fetch_tiles gis_terenuri 12 2300 2310 1490 1498
fetch_tiles gis_cladiri 12 2300 2310 1490 1498
# Cluj area (z12)
fetch_tiles gis_terenuri 12 2264 2270 1460 1465
fetch_tiles gis_cladiri 12 2264 2270 1460 1465

echo "[$(date -Iseconds)] Fetching tiles ($PARALLEL concurrent)..."

# Pipe all URLs through xargs+curl for parallel fetching
fetch_tiles gis_uats_z5 5 17 18 11 11
fetch_tiles gis_uats_z8 7 69 73 44 46
fetch_tiles gis_uats_z8 8 139 147 88 92
fetch_tiles gis_uats_z8 9 279 288 177 185
fetch_tiles gis_terenuri 12 2300 2310 1490 1498
fetch_tiles gis_cladiri 12 2300 2310 1490 1498
fetch_tiles gis_terenuri 12 2264 2270 1460 1465
fetch_tiles gis_cladiri 12 2264 2270 1460 1465

# Actually execute all fetches
{
  fetch_tiles gis_uats_z5 5 17 18 11 11
  fetch_tiles gis_uats_z8 7 69 73 44 46
  fetch_tiles gis_uats_z8 8 139 147 88 92
  fetch_tiles gis_uats_z8 9 279 288 177 185
  fetch_tiles gis_terenuri 12 2300 2310 1490 1498
  fetch_tiles gis_cladiri 12 2300 2310 1490 1498
  fetch_tiles gis_terenuri 12 2264 2270 1460 1465
  fetch_tiles gis_cladiri 12 2264 2270 1460 1465
} | xargs -P "$PARALLEL" -I {} curl -sf -o /dev/null {} 2>/dev/null

echo "[$(date -Iseconds)] Cache warming complete."
