# =============================================================================
#  Dockerfile — DemIA HF Object Detection Starter
#
#  Builds a production-ready container that serves the FastAPI detection API.
#
#  Build:
#    docker build -t demia-object-detection .
#
#  Run (CPU):
#    docker run -p 8000:8000 demia-object-detection
#
#  Run (GPU — requires nvidia-docker):
#    docker run --gpus all -p 8000:8000 \
#      -e HF_MODEL_ID=facebook/detr-resnet-50 \
#      demia-object-detection
#
#  Override the model at runtime:
#    docker run -p 8000:8000 -e HF_MODEL_ID=hustvl/yolos-small demia-object-detection
# =============================================================================

# ── Base image ────────────────────────────────────────────────────────────────
# python:3.11-slim keeps the image small; switch to nvidia/cuda:12.1.0-... for GPU.
FROM python:3.11-slim

# ── Build arguments ───────────────────────────────────────────────────────────
ARG TORCH_INDEX=https://download.pytorch.org/whl/cpu
ARG APP_PORT=8000

# ── System dependencies ───────────────────────────────────────────────────────
RUN apt-get update && apt-get install -y --no-install-recommends \
    # Pillow / image support
    libjpeg-dev \
    libpng-dev \
    libwebp-dev \
    # libGL for potential OpenCV compatibility (optional)
    libglib2.0-0 \
    # Clean up
    && rm -rf /var/lib/apt/lists/*

# ── Working directory ─────────────────────────────────────────────────────────
WORKDIR /app

# ── Python dependencies ───────────────────────────────────────────────────────
# Copy dependency files first for Docker layer caching.
COPY requirements.txt pyproject.toml ./

# Install PyTorch (CPU wheel by default; override ARG for GPU).
RUN pip install --no-cache-dir torch torchvision \
    --index-url "$TORCH_INDEX"

# Install remaining project dependencies.
RUN pip install --no-cache-dir -r requirements.txt

# ── Application source ────────────────────────────────────────────────────────
COPY config/  ./config/
COPY src/     ./src/
COPY api/     ./api/
COPY .env.example .env.example

# ── HF model cache volume ─────────────────────────────────────────────────────
# Mount a volume here to persist downloaded weights across container restarts:
#   docker run -v hf_cache:/root/.cache/huggingface ...
ENV HF_HOME=/root/.cache/huggingface
VOLUME /root/.cache/huggingface

# ── Environment defaults (override with -e or --env-file) ────────────────────
ENV HF_MODEL_ID=hustvl/yolos-tiny \
    CONFIDENCE_THRESH=0.5 \
    OUTPUT_DIR=/app/outputs \
    LOG_LEVEL=INFO \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

# ── Non-root user for security ────────────────────────────────────────────────
RUN useradd -m -u 1000 appuser && \
    mkdir -p /app/outputs && \
    chown -R appuser:appuser /app /root/.cache
USER appuser

# ── Port ──────────────────────────────────────────────────────────────────────
EXPOSE $APP_PORT

# ── Health check ─────────────────────────────────────────────────────────────
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:${APP_PORT}/health')" \
    || exit 1

# ── Entrypoint ────────────────────────────────────────────────────────────────
CMD ["uvicorn", "api.main:app", \
     "--host", "0.0.0.0", \
     "--port", "8000", \
     "--workers", "1"]
