# ---------------------------------------------------------------------------
# GPS-Denied Onboard — Production Dockerfile
# ---------------------------------------------------------------------------
# Build: docker build -t gps-denied-onboard .
# Run:   docker run -p 8000:8000 gps-denied-onboard
#
# Jetson Orin Nano Super deployment: use base image
#   nvcr.io/nvidia/l4t-pytorch:r36.2.0-pth2.1-py3
# and replace python:3.11-slim with that image.
# ---------------------------------------------------------------------------

FROM python:3.11-slim AS builder

WORKDIR /build

# System deps for OpenCV headless + numpy compilation
RUN apt-get update && apt-get install -y --no-install-recommends \
        gcc \
        libgl1 \
        libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

COPY pyproject.toml .
# Install only the package metadata (no source yet) to cache deps layer
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -e "." --no-build-isolation

# ---------------------------------------------------------------------------
FROM python:3.11-slim AS runtime

WORKDIR /app

# Runtime system deps (OpenCV headless needs libGL + libglib)
RUN apt-get update && apt-get install -y --no-install-recommends \
        libgl1 \
        libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

# Copy installed packages from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy application source
COPY src/ src/
COPY pyproject.toml .

# Runtime environment
ENV PYTHONPATH=/app/src \
    DB_URL=sqlite+aiosqlite:////data/flights.db \
    SATELLITE_TILE_DIR=/data/satellite_tiles \
    MAVLINK_CONNECTION=udp:127.0.0.1:14550

# Data volume: database + satellite tiles
VOLUME ["/data"]

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1

CMD ["uvicorn", "gps_denied.app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
