#!/usr/bin/env bash
set -Eeuo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENDPOINT="${1:-${AGRARIAN_TILE_SERVER_URL:-http://192.168.5.14:18080}}"
ENDPOINT="${ENDPOINT%/}"
CACHE_ROOT="${AGRARIAN_TILE_CLIENT_CACHE:-/tmp/agrarian-tile-client-cache-${USER:-user}}"
URL_LIST="${CACHE_ROOT}/download-list.txt"
REDOWNLOAD_REL=""

log() {
  printf '[agrarian-tile-client] %s\n' "$*"
}

download_path() {
  local rel="$1"
  local target="${CACHE_ROOT}/${rel#./}"
  mkdir -p "$(dirname "$target")"
  curl -fsS "${ENDPOINT}/${rel#./}" -o "$target"
}

rm -rf "${CACHE_ROOT}"
mkdir -p "${CACHE_ROOT}"

log "Endpoint: ${ENDPOINT}"

download_path "manifest.json"

python3 - "${CACHE_ROOT}/manifest.json" "${URL_LIST}" <<'PY'
import json
import sys
from pathlib import Path

manifest_path = Path(sys.argv[1])
url_list_path = Path(sys.argv[2])

manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
if manifest.get("service") != "agrarian-tile-delivery":
    raise SystemExit("unexpected service in manifest")

packages = manifest.get("tile_packages") or []
if len(packages) != 1:
    raise SystemExit(f"expected exactly one tile package, found {len(packages)}")

package = packages[0]
base_url = package["base_url"].strip("/")
terrain = package.get("terrain") or {}
if "heightmap_r16" not in terrain:
    raise SystemExit("manifest is missing terrain.heightmap_r16")

paths = [
    "manifest.json",
    manifest["tiles_registry"].strip("/"),
    "SHA256SUMS",
]
paths.extend(f"{base_url}/{value}" for value in terrain.values())

url_list_path.write_text("\n".join(paths) + "\n", encoding="utf-8")
print(f"{base_url}/{terrain['heightmap_r16']}")
PY

while IFS= read -r rel; do
  [[ -n "$rel" ]] || continue
  log "Downloading ${rel}"
  download_path "$rel"
done < "${URL_LIST}"

while read -r _checksum rel; do
  [[ -n "${rel:-}" ]] || continue
  rel="${rel#./}"
  if [[ ! -f "${CACHE_ROOT}/${rel}" ]]; then
    log "Downloading checksum-listed file ${rel}"
    download_path "$rel"
  fi
done < "${CACHE_ROOT}/SHA256SUMS"

(
  cd "${CACHE_ROOT}"
  sha256sum -c SHA256SUMS >/dev/null
)

python3 - "${CACHE_ROOT}/manifest.json" "${CACHE_ROOT}/ground_zero_tiles.json" <<'PY'
import json
import sys
from pathlib import Path

manifest = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
registry = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
default_tile = manifest["default_tile_id"]

tiles = registry.get("tiles") or []
matches = [tile for tile in tiles if tile.get("tile_id") == default_tile]
if not matches:
    raise SystemExit(f"default tile not found in registry: {default_tile}")

neighbors = matches[0].get("neighbors") or {}
if not neighbors:
    raise SystemExit("default tile has no neighbor metadata")

print(f"registry_tile={default_tile}")
print(f"neighbor_count={len(neighbors)}")
PY

REDOWNLOAD_REL="$(head -1 "${URL_LIST}")"
REDOWNLOAD_REL="$(python3 - "${CACHE_ROOT}/manifest.json" <<'PY'
import json
import sys
from pathlib import Path

manifest = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
package = manifest["tile_packages"][0]
base_url = package["base_url"].strip("/")
print(f"{base_url}/{package['terrain']['heightmap_r16']}")
PY
)"

rm -f "${CACHE_ROOT}/${REDOWNLOAD_REL}"
log "Redownloading ${REDOWNLOAD_REL}"
download_path "${REDOWNLOAD_REL}"

(
  cd "${CACHE_ROOT}"
  sha256sum -c SHA256SUMS >/dev/null
)

log "Tile lookup, download, cache checksum, and redownload verification passed."
log "Cache: ${CACHE_ROOT}"
