FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates libgomp1 libheif1 libimage-exiftool-perl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY app/ ./

ARG LEAFLET_VERSION=1.9.4
RUN LEAFLET_VERSION="$LEAFLET_VERSION" python - <<'PY'
from pathlib import Path
import os
import urllib.request

version = os.environ["LEAFLET_VERSION"]
base = Path("/app/static/vendor/leaflet")
(base / "images").mkdir(parents=True, exist_ok=True)
files = {
    "leaflet.css": "leaflet.css",
    "leaflet.js": "leaflet.js",
    "images/marker-icon.png": "images/marker-icon.png",
    "images/marker-icon-2x.png": "images/marker-icon-2x.png",
    "images/marker-shadow.png": "images/marker-shadow.png",
}
mirrors = (
    f"https://unpkg.com/leaflet@{version}/dist",
    f"https://cdn.jsdelivr.net/npm/leaflet@{version}/dist",
)
for destination, source in files.items():
    target = base / destination
    last_error = None
    for mirror in mirrors:
        try:
            urllib.request.urlretrieve(f"{mirror}/{source}", target)
            break
        except Exception as exc:  # build-time fallback to the second CDN
            last_error = exc
    else:
        raise RuntimeError(f"Could not download Leaflet asset {source}: {last_error}")
PY

EXPOSE 8080

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--proxy-headers", "--forwarded-allow-ips=*"]
