#!/usr/bin/env bash
# tile-cache-stats.sh — Show tile cache hit/miss statistics
# Usage: ./scripts/tile-cache-stats.sh [MINUTES]
# Reads recent nginx logs from tile-cache container.

set -euo pipefail

MINUTES="${1:-60}"

echo "=== Tile Cache Stats (last ${MINUTES}min) ==="
echo ""

# Get nginx status (active connections)
echo "--- Connections ---"
curl -s "http://10.10.10.166:3010/status" 2>/dev/null || echo "(status endpoint unavailable)"
echo ""

# Parse recent logs for cache hit/miss ratio
echo "--- Cache Performance ---"
docker logs tile-cache --since "${MINUTES}m" 2>/dev/null | \
  grep -oP 'cache=\K\w+' | sort | uniq -c | sort -rn || echo "(no logs in timeframe)"

echo ""
echo "--- Cache Size ---"
docker exec tile-cache du -sh /var/cache/nginx/tiles/ 2>/dev/null || echo "(cannot read cache dir)"

echo ""
echo "--- Slowest Tiles (>1s) ---"
docker logs tile-cache --since "${MINUTES}m" 2>/dev/null | \
  grep -oP 'time=\K[0-9.]+' | awk '$1 > 1.0 {print $1"s"}' | sort -rn | head -5 || echo "(none)"
