# ─────────────────────────────────────────────────────────────────────────────
# Dockerfile — TensorFlow Transfer Learning Starter
#
# Builds a production-ready image that serves the FastAPI prediction API.
#
# Build:
#   docker build -t tf-transfer-learning .
#
# Run API:
#   docker run -p 8000:8000 \
#     -v $(pwd)/checkpoints:/app/checkpoints \
#     -v $(pwd)/config:/app/config \
#     tf-transfer-learning
#
# Run training inside a container:
#   docker run --rm \
#     -v $(pwd)/data:/app/data \
#     -v $(pwd)/checkpoints:/app/checkpoints \
#     tf-transfer-learning \
#     python scripts/run.py --mode train
#
# For GPU support, replace the base image with:
#   tensorflow/tensorflow:2.15.0-gpu
# and run with: docker run --gpus all …
# ─────────────────────────────────────────────────────────────────────────────

FROM tensorflow/tensorflow:2.15.0 AS base

LABEL maintainer="DemIA Living Lab — USAL / BISITE <bisite@usal.es>"
LABEL description="TensorFlow Transfer Learning Starter — image classification API"
LABEL version="0.1.0"

# Suppress TensorFlow C++ info logs inside the container.
ENV TF_CPP_MIN_LOG_LEVEL=2
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /app

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

# ── Copy source code ──────────────────────────────────────────────────────────
COPY src/       src/
COPY api/       api/
COPY app/       app/
COPY scripts/   scripts/
COPY examples/  examples/
COPY config/    config/
COPY .env.example .env.example

# ── Create runtime directories ────────────────────────────────────────────────
RUN mkdir -p checkpoints logs data

# ── Non-root user for security ────────────────────────────────────────────────
RUN useradd --create-home --no-log-init appuser && \
    chown -R appuser:appuser /app
USER appuser

# ── Expose API port ───────────────────────────────────────────────────────────
EXPOSE 8000

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

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