# ─────────────────────────────────────────────────────────────────────────────
# Dockerfile — TensorFlow Object Detection Starter (API service)
# DemIA Living Lab — Universidad de Salamanca (USAL) / BISITE
#
# Build:
#   docker build -t demia-od-starter .
#
# Run (API only):
#   docker run -p 8000:8000 demia-od-starter
#
# For the full stack (API + UI) use docker-compose.yml.
# ─────────────────────────────────────────────────────────────────────────────

FROM python:3.11-slim AS base

LABEL maintainer="DemIA Living Lab <bisite@usal.es>"
LABEL description="TensorFlow Object Detection Starter — DemIA Living Lab"

# Keeps Python from generating .pyc files and buffers stdout/stderr.
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    TF_CPP_MIN_LOG_LEVEL=2 \
    # Disable GPU inside the container (CPU-only inference)
    CUDA_VISIBLE_DEVICES=-1

WORKDIR /app

# ── System dependencies ────────────────────────────────────────────────────────
# libgl1 and libglib2.0 are required by opencv-python-headless
RUN apt-get update && apt-get install -y --no-install-recommends \
    libgl1 \
    libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

# ── Python dependencies ────────────────────────────────────────────────────────
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

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

# Create runtime directories
RUN mkdir -p checkpoints logs outputs

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

EXPOSE 8000

# Default: start the FastAPI API server
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
