#!/bin/bash
# Setup Photon (Komoot) geocoder docker container with pre-built RO extract.
# Photon = Java service with embedded OpenSearch index over OSM admin polygons + addresses.
#
# Source: https://download1.graphhopper.com/public/extracts/by-country-code/ro/
# Size:   ~332MB tar.bz2 → ~3GB extracted
# API:    HTTP on :2322, ?q=Strada+X+Bucuresti returns GeoJSON with coords + admin matches.

set -euo pipefail

PHOTON_DIR=/opt/photon
EXTRACT_BASE=https://download1.graphhopper.com/public/extracts/by-country-code/ro

log() { echo "[$(date '+%H:%M:%S')] $1"; }

log "=== Photon setup ==="

# 1. Download extract — graphhopper publishes dated snapshots (photon-db-ro-YYMMDD.tar.bz2);
# the "-latest" alias is unreliable, so we auto-pick the newest dated file from the index.
sudo mkdir -p "$PHOTON_DIR"
cd "$PHOTON_DIR"

if [ ! -d "$PHOTON_DIR/photon_data" ]; then
  LATEST=$(curl -fsSL "$EXTRACT_BASE/" \
    | grep -oE 'photon-db-ro-[0-9]{6}\.tar\.bz2' \
    | sort -u | tail -1)
  if [ -z "$LATEST" ]; then
    log "FATAL: could not discover latest Photon RO extract from $EXTRACT_BASE/"
    exit 1
  fi
  log "Downloading $LATEST (~332MB)..."
  sudo curl -fL "$EXTRACT_BASE/$LATEST" -o photon-ro.tar.bz2
  log "Extracting (creates ~3GB photon_data/)..."
  sudo tar -xjf photon-ro.tar.bz2
  sudo rm photon-ro.tar.bz2
  sudo chown -R 1000:1000 "$PHOTON_DIR"
else
  log "photon_data/ already exists; skipping download"
fi

# 2. Run docker container
if docker ps --filter name=photon-ro --format '{{.Names}}' | grep -q photon-ro; then
  log "photon-ro already running"
else
  log "Starting photon-ro container..."
  docker rm -f photon-ro 2>/dev/null || true
  docker run -d --name photon-ro --restart unless-stopped \
    -p 127.0.0.1:2322:2322 \
    -v "$PHOTON_DIR/photon_data:/photon/photon_data" \
    rtuszik/photon-docker:latest
fi

# 3. Wait for startup, smoke test
log "Waiting for Photon to initialize..."
for i in $(seq 1 30); do
  if curl -fs "http://localhost:2322/api?q=Bucuresti" >/dev/null 2>&1; then
    log "Photon ready."
    break
  fi
  sleep 2
done

# 4. Smoke tests
log "Smoke test 1 — Bucuresti:"
curl -fs "http://localhost:2322/api?q=Bucuresti&limit=2" | head -c 400
echo
log "Smoke test 2 — Cluj-Napoca Strada Memorandumului:"
curl -fs "http://localhost:2322/api?q=Strada+Memorandumului+Cluj-Napoca&limit=1" | head -c 400
echo
log "=== Photon setup complete (HTTP API on 127.0.0.1:2322) ==="
