#!/usr/bin/env bash
# benches/bench-e2e.sh — End-to-end pipeline benchmark for geolith
#
# Downloads all required data and benchmarks geolith on a configurable region.
# Designed to run in isolation on any machine with Rust and basic CLI tools.
#
# Usage:
#   ./benches/bench-e2e.sh                    # Default: Goa, India (small)
#   ./benches/bench-e2e.sh --preset mumbai    # Mumbai metro area
#   ./benches/bench-e2e.sh --preset western   # Western India (larger)
#   ./benches/bench-e2e.sh --bbox 72.7,18.8,73.1,19.3 --max-zoom 14
#   ./benches/bench-e2e.sh --clean            # Remove all downloaded data
#   ./benches/bench-e2e.sh --download-only    # Download data without running
#
# Requirements:
#   - Rust toolchain (1.85+) with protoc
#   - curl
#   - unzip
#   - ~2 GB disk for downloads (shapefiles + NE + OSM)
#   - osmium-tool (optional, for bbox extraction from large PBF)

set -euo pipefail

# ---------------------------------------------------------------------------
# Defaults
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DATA_DIR="${PROJECT_ROOT}/bench-data"
MAX_ZOOM=14
BBOX=""
PRESET="goa"
CLEAN=false
DOWNLOAD_ONLY=false
SKIP_BUILD=false
THREADS=""
VERBOSE=false

# ---------------------------------------------------------------------------
# Presets (bbox, osm_region, description)
# ---------------------------------------------------------------------------
declare -A PRESET_BBOX
PRESET_BBOX[goa]="73.5,14.8,74.5,15.8"
PRESET_BBOX[mumbai]="72.7,18.8,73.1,19.3"
PRESET_BBOX[western]="67.67,14.39,80.92,24.72"
PRESET_BBOX[india]="68.0,6.5,97.5,37.2"

declare -A PRESET_DESC
PRESET_DESC[goa]="Goa, India (small state, ~5 min)"
PRESET_DESC[mumbai]="Mumbai metro (dense city, ~3 min)"
PRESET_DESC[western]="Western India (large region, ~5-10 min)"
PRESET_DESC[india]="Full India (very large, ~30+ min)"

# All presets use the India PBF from Geofabrik
OSM_URL="https://download.geofabrik.de/asia/india-latest.osm.pbf"
OSM_FILE="india-latest.osm.pbf"

# Static data sources
NE_URL="https://naciscdn.org/naturalearth/packages/natural_earth_vector.sqlite.zip"
NE_FILE="natural_earth_vector.sqlite"

LAND_URL="https://osmdata.openstreetmap.de/download/land-polygons-split-3857.zip"
LAND_DIR="land-polygons-split-3857"

WATER_URL="https://osmdata.openstreetmap.de/download/water-polygons-split-3857.zip"
WATER_DIR="water-polygons-split-3857"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

log()  { echo -e "${BLUE}[bench]${NC} $*"; }
ok()   { echo -e "${GREEN}[bench]${NC} $*"; }
warn() { echo -e "${YELLOW}[bench]${NC} $*"; }
err()  { echo -e "${RED}[bench]${NC} $*" >&2; }
die()  { err "$@"; exit 1; }

human_size() {
    local bytes=$1
    if   (( bytes >= 1073741824 )); then printf "%.1f GB" "$(echo "scale=1; $bytes / 1073741824" | bc)"
    elif (( bytes >= 1048576 ));    then printf "%.0f MB" "$(echo "scale=0; $bytes / 1048576" | bc)"
    elif (( bytes >= 1024 ));       then printf "%.0f KB" "$(echo "scale=0; $bytes / 1024" | bc)"
    else printf "%d B" "$bytes"
    fi
}

check_cmd() {
    command -v "$1" &>/dev/null
}

# Download with resume support and progress
download() {
    local url="$1" dest="$2"
    if [[ -f "$dest" ]]; then
        ok "Already downloaded: $(basename "$dest")"
        return 0
    fi
    log "Downloading $(basename "$dest")..."
    log "  URL: $url"
    curl -fSL --progress-bar -o "${dest}.tmp" "$url"
    mv "${dest}.tmp" "$dest"
    ok "Downloaded: $(basename "$dest") ($(human_size "$(stat -f%z "$dest" 2>/dev/null || stat -c%s "$dest" 2>/dev/null)"))"
}

# ---------------------------------------------------------------------------
# Parse arguments
# ---------------------------------------------------------------------------
usage() {
    cat <<EOF
${BOLD}geolith end-to-end benchmark${NC}

Downloads all required data and benchmarks geolith on a configurable region.

${BOLD}USAGE:${NC}
    $(basename "$0") [OPTIONS]

${BOLD}OPTIONS:${NC}
    --preset NAME       Region preset: goa (default), mumbai, western, india
    --bbox BBOX         Custom bounding box (min_lon,min_lat,max_lon,max_lat)
    --max-zoom ZOOM     Maximum zoom level (default: 14)
    --data-dir DIR      Data directory (default: ./bench-data)
    --threads N         Thread count (default: all cores)
    --skip-build        Skip cargo build --release
    --download-only     Download data without running benchmark
    --clean             Remove all downloaded data
    --verbose           Show detailed output
    --help              Show this help

${BOLD}PRESETS:${NC}
    goa                 ${PRESET_DESC[goa]}
    mumbai              ${PRESET_DESC[mumbai]}
    western             ${PRESET_DESC[western]}
    india               ${PRESET_DESC[india]}

${BOLD}EXAMPLES:${NC}
    # Quick benchmark on Goa (smallest)
    $(basename "$0")

    # Custom bbox with max-zoom 15
    $(basename "$0") --bbox 72.7,18.8,73.1,19.3 --max-zoom 15

    # Large benchmark on western India
    $(basename "$0") --preset western --max-zoom 15

${BOLD}REQUIREMENTS:${NC}
    - Rust toolchain (1.85+) with protoc
    - curl, unzip
    - ~2 GB disk for base data (shapefiles + NE + OSM)
    - osmium-tool (optional, for fast PBF bbox extraction)
EOF
    exit 0
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --preset)      PRESET="$2"; shift 2 ;;
        --bbox)        BBOX="$2"; shift 2 ;;
        --max-zoom)    MAX_ZOOM="$2"; shift 2 ;;
        --data-dir)    DATA_DIR="$2"; shift 2 ;;
        --threads)     THREADS="$2"; shift 2 ;;
        --skip-build)  SKIP_BUILD=true; shift ;;
        --download-only) DOWNLOAD_ONLY=true; shift ;;
        --clean)       CLEAN=true; shift ;;
        --verbose)     VERBOSE=true; shift ;;
        --help|-h)     usage ;;
        *) die "Unknown option: $1 (use --help for usage)" ;;
    esac
done

# Resolve bbox from preset if not explicitly set
if [[ -z "$BBOX" ]]; then
    if [[ -v "PRESET_BBOX[$PRESET]" ]]; then
        BBOX="${PRESET_BBOX[$PRESET]}"
    else
        die "Unknown preset: $PRESET (available: goa, mumbai, western, india)"
    fi
fi

# ---------------------------------------------------------------------------
# Clean mode
# ---------------------------------------------------------------------------
if $CLEAN; then
    log "Cleaning benchmark data directory: $DATA_DIR"
    rm -rf "$DATA_DIR"
    ok "Cleaned."
    exit 0
fi

# ---------------------------------------------------------------------------
# Preflight checks
# ---------------------------------------------------------------------------
log "Checking requirements..."

check_cmd curl    || die "curl is required but not found"
check_cmd unzip   || die "unzip is required but not found"
check_cmd cargo   || die "cargo (Rust toolchain) is required but not found"
check_cmd protoc  || die "protoc (Protocol Buffers compiler) is required but not found"
check_cmd bc      || die "bc is required but not found"

if check_cmd osmium; then
    HAS_OSMIUM=true
    ok "osmium found — will use for fast PBF bbox extraction"
else
    HAS_OSMIUM=false
    warn "osmium not found — geolith will handle PBF filtering internally (slower)"
    warn "  Install: brew install osmium-tool (macOS) or apt install osmium-tool (Ubuntu)"
fi

# ---------------------------------------------------------------------------
# Print configuration
# ---------------------------------------------------------------------------
echo ""
echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo -e "${BOLD}  geolith end-to-end benchmark${NC}"
echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo -e "  Preset:    ${PRESET}"
echo -e "  Bbox:      ${BBOX}"
echo -e "  Max zoom:  ${MAX_ZOOM}"
echo -e "  Data dir:  ${DATA_DIR}"
[[ -n "$THREADS" ]] && echo -e "  Threads:   ${THREADS}"
echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo ""

# ---------------------------------------------------------------------------
# Create data directory
# ---------------------------------------------------------------------------
mkdir -p "$DATA_DIR"/{sources,output,tmp}

# ---------------------------------------------------------------------------
# Phase 1: Download data
# ---------------------------------------------------------------------------
log "Phase 1: Download data"
echo ""

# --- OSM PBF ---
download "$OSM_URL" "$DATA_DIR/sources/$OSM_FILE"

# --- Natural Earth ---
if [[ -f "$DATA_DIR/sources/$NE_FILE" ]]; then
    ok "Already extracted: $NE_FILE"
else
    download "$NE_URL" "$DATA_DIR/sources/${NE_FILE}.zip"
    log "Extracting Natural Earth SQLite..."
    unzip -oq "$DATA_DIR/sources/${NE_FILE}.zip" "packages/$NE_FILE" -d "$DATA_DIR/sources/"
    mv "$DATA_DIR/sources/packages/$NE_FILE" "$DATA_DIR/sources/$NE_FILE"
    rmdir "$DATA_DIR/sources/packages" 2>/dev/null || true
    ok "Extracted: $NE_FILE"
fi

# --- Land polygons ---
if [[ -d "$DATA_DIR/sources/$LAND_DIR" && -f "$DATA_DIR/sources/$LAND_DIR/land_polygons.shp" ]]; then
    ok "Already extracted: $LAND_DIR"
else
    download "$LAND_URL" "$DATA_DIR/sources/${LAND_DIR}.zip"
    log "Extracting land polygons (this may take a moment)..."
    unzip -oq "$DATA_DIR/sources/${LAND_DIR}.zip" -d "$DATA_DIR/sources/"
    ok "Extracted: $LAND_DIR"
fi

# --- Water polygons ---
if [[ -d "$DATA_DIR/sources/$WATER_DIR" && -f "$DATA_DIR/sources/$WATER_DIR/water_polygons.shp" ]]; then
    ok "Already extracted: $WATER_DIR"
else
    download "$WATER_URL" "$DATA_DIR/sources/${WATER_DIR}.zip"
    log "Extracting water polygons (this may take a moment)..."
    unzip -oq "$DATA_DIR/sources/${WATER_DIR}.zip" -d "$DATA_DIR/sources/"
    ok "Extracted: $WATER_DIR"
fi

echo ""
log "All data downloaded."
echo ""

# --- Disk usage summary ---
log "Disk usage:"
du -sh "$DATA_DIR/sources/"* 2>/dev/null | while read -r size path; do
    echo "  $size  $(basename "$path")"
done
echo ""

if $DOWNLOAD_ONLY; then
    ok "Download complete (--download-only). Exiting."
    exit 0
fi

# ---------------------------------------------------------------------------
# Phase 2: Build geolith
# ---------------------------------------------------------------------------
if $SKIP_BUILD; then
    log "Phase 2: Build (skipped via --skip-build)"
    GEOLITH_BIN="$PROJECT_ROOT/target/release/geolith"
    [[ -f "$GEOLITH_BIN" ]] || die "No release binary found at $GEOLITH_BIN. Run without --skip-build."
else
    log "Phase 2: Building geolith (release mode)..."
    (cd "$PROJECT_ROOT" && cargo build --release 2>&1)
    GEOLITH_BIN="$PROJECT_ROOT/target/release/geolith"
    ok "Build complete: $GEOLITH_BIN"
fi
echo ""

# ---------------------------------------------------------------------------
# Phase 3: Run benchmark
# ---------------------------------------------------------------------------
log "Phase 3: Running geolith benchmark"
echo ""

OUTPUT_FILE="$DATA_DIR/output/benchmark.pmtiles"
LOG_FILE="$DATA_DIR/output/benchmark.log"
NODE_STORE="$DATA_DIR/tmp/geolith-nodes.bin"
TMP_DIR="$DATA_DIR/tmp"

# Clean previous output
rm -f "$OUTPUT_FILE" "$LOG_FILE"

# Build command
CMD=(
    "$GEOLITH_BIN"
    --data "$DATA_DIR/sources"
    --osm-pbf "$DATA_DIR/sources/$OSM_FILE"
    --natural-earth "$DATA_DIR/sources/$NE_FILE"
    --land-polygons "$DATA_DIR/sources/$LAND_DIR"
    --water-polygons "$DATA_DIR/sources/$WATER_DIR"
    --output "$OUTPUT_FILE"
    --bbox "$BBOX"
    --max-zoom "$MAX_ZOOM"
    --node-store "$NODE_STORE"
    --node-cache
    --tmpdir "$TMP_DIR"
    --landcover-source none
    --bathymetry-source none
)

[[ -n "$THREADS" ]] && CMD+=(--threads "$THREADS")

log "Command:"
echo "  ${CMD[*]}"
echo ""

# Run with timing
SECONDS=0
{ time "${CMD[@]}" 2>&1; } 2>&1 | tee "$LOG_FILE"
ELAPSED=$SECONDS
echo ""

# ---------------------------------------------------------------------------
# Phase 4: Report results
# ---------------------------------------------------------------------------
log "Phase 4: Results"
echo ""

# Output size
if [[ -f "$OUTPUT_FILE" ]]; then
    OUTPUT_SIZE=$(stat -f%z "$OUTPUT_FILE" 2>/dev/null || stat -c%s "$OUTPUT_FILE" 2>/dev/null)
    OUTPUT_HUMAN=$(human_size "$OUTPUT_SIZE")
else
    OUTPUT_HUMAN="(no output file)"
fi

# Extract tile count from log
TILE_COUNT=$(grep -o '[0-9,]* tiles written' "$LOG_FILE" | tail -1 | grep -o '[0-9,]*' || echo "unknown")

# Extract feature counts from log
TOTAL_FEATURES=$(grep "Phase 1 complete" "$LOG_FILE" | grep -o '[0-9]* features' | head -1 | grep -o '[0-9]*' || echo "unknown")
TILE_FEATURES=$(grep "Phase 1 complete" "$LOG_FILE" | grep -o '[0-9]* tile features' | head -1 | grep -o '[0-9]*' || echo "unknown")

# System info
OS=$(uname -s)
ARCH=$(uname -m)
CORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo "?")
RAM_KB=$(grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}')
if [[ -n "$RAM_KB" ]]; then
    RAM="$(( RAM_KB / 1048576 )) GB"
else
    RAM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || echo "")
    if [[ -n "$RAM_BYTES" ]]; then
        RAM="$(( RAM_BYTES / 1073741824 )) GB"
    else
        RAM="?"
    fi
fi

echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo -e "${BOLD}  BENCHMARK RESULTS${NC}"
echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${BOLD}Configuration${NC}"
echo -e "  Preset:          ${PRESET}"
echo -e "  Bbox:            ${BBOX}"
echo -e "  Max zoom:        ${MAX_ZOOM}"
echo ""
echo -e "  ${BOLD}System${NC}"
echo -e "  OS:              ${OS} ${ARCH}"
echo -e "  CPU cores:       ${CORES}"
echo -e "  RAM:             ${RAM}"
echo ""
echo -e "  ${BOLD}Results${NC}"
echo -e "  Wall time:       ${BOLD}${ELAPSED}s$(if (( ELAPSED >= 60 )); then printf " (%d:%02d)" $((ELAPSED/60)) $((ELAPSED%60)); fi)${NC}"
echo -e "  Output size:     ${BOLD}${OUTPUT_HUMAN}${NC}"
echo -e "  Tiles written:   ${TILE_COUNT}"
echo -e "  Input features:  ${TOTAL_FEATURES}"
echo -e "  Tile features:   ${TILE_FEATURES}"
echo ""
echo -e "${BOLD}═══════════════════════════════════════════════════${NC}"
echo ""

# Write results to JSON for machine consumption
RESULTS_JSON="$DATA_DIR/output/results.json"
cat > "$RESULTS_JSON" <<EOF
{
  "tool": "geolith",
  "version": "0.1.0",
  "preset": "${PRESET}",
  "bbox": "${BBOX}",
  "max_zoom": ${MAX_ZOOM},
  "wall_time_seconds": ${ELAPSED},
  "output_size_bytes": ${OUTPUT_SIZE:-0},
  "tiles_written": "${TILE_COUNT}",
  "input_features": "${TOTAL_FEATURES}",
  "tile_features": "${TILE_FEATURES}",
  "system": {
    "os": "${OS}",
    "arch": "${ARCH}",
    "cores": "${CORES}",
    "ram": "${RAM}"
  },
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
ok "Results saved to: $RESULTS_JSON"
ok "Full log saved to: $LOG_FILE"
echo ""

# Clean up sort chunks
if [[ -d "$TMP_DIR" ]]; then
    CHUNK_COUNT=$(find "$TMP_DIR" -name "chunk_*.bin" 2>/dev/null | wc -l | tr -d ' ')
    if (( CHUNK_COUNT > 0 )); then
        log "Cleaning $CHUNK_COUNT sort chunks from tmp/..."
        rm -f "$TMP_DIR"/chunk_*.bin
    fi
fi

ok "Benchmark complete."
