# ─────────────────────────────────────────────────────────────────────────────
# Dockerfile — TensorFlow Basic Project Starter
# DemIA Living Lab — Universidad de Salamanca / BISITE
#
# Builds a CPU-only image that can run both the training script and the
# FastAPI inference service.
#
# Build:
#   docker build -t tf-starter:latest .
#
# Train inside the container (mounts local checkpoints/logs for persistence):
#   docker run --rm \
#     -v $(pwd)/checkpoints:/app/checkpoints \
#     -v $(pwd)/logs:/app/logs \
#     tf-starter:latest python scripts/run.py --mode train
#
# Serve the API:
#   docker run --rm -p 8000:8000 \
#     -v $(pwd)/checkpoints:/app/checkpoints \
#     tf-starter:latest
#
# GPU note: replace the base image with tensorflow/tensorflow:2.15.0-gpu and
# run with `docker run --gpus all …`
# ─────────────────────────────────────────────────────────────────────────────

# ── Stage 1: Build dependencies ───────────────────────────────────────────────
FROM python:3.11-slim AS builder

WORKDIR /build

# System dependencies for compiling some Python packages.
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --upgrade pip && \
    pip install --no-cache-dir --prefix=/install -r requirements.txt


# ── Stage 2: Runtime image ────────────────────────────────────────────────────
FROM python:3.11-slim AS runtime

LABEL maintainer="DemIA Living Lab — USAL/BISITE"
LABEL description="TensorFlow Basic Project Starter — CPU inference service"

WORKDIR /app

# Copy installed packages from the builder stage.
COPY --from=builder /install /usr/local

# Copy application source.
COPY src/       ./src/
COPY api/       ./api/
COPY config/    ./config/
COPY scripts/   ./scripts/
COPY .env.example .env.example

# Create directories that the application writes to at runtime.
RUN mkdir -p checkpoints logs data

# Expose FastAPI port.
EXPOSE 8000

# Reduce TF verbosity in container logs.
ENV TF_CPP_MIN_LOG_LEVEL=2
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

# Default command: start the FastAPI service.
# Override at runtime with `docker run … python scripts/run.py --mode train`
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]
