# syntax=docker/dockerfile:1.7
# ──────────────────────────────────────────────────────────────────────────
# Forensic Features API — Lean Container
#
# Imagine finală estimată: ~1.5 GB
# (vs ~8 GB cu transformers/torch/autogluon — neincluse aici)
#
# Build:    docker build -t forensic-features:latest .
# Run:      docker run -p 8080:8080 forensic-features:latest
# ──────────────────────────────────────────────────────────────────────────


# ═══ Stage 1: Builder ═══════════════════════════════════════════════════
FROM python:3.12-slim-bookworm AS builder

RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential \
        gcc \
        g++ \
    && rm -rf /var/lib/apt/lists/*

ENV VIRTUAL_ENV=/opt/venv
RUN python -m venv $VIRTUAL_ENV
ENV PATH="$VIRTUAL_ENV/bin:$PATH"

RUN pip install --no-cache-dir --upgrade pip setuptools wheel

COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir -r /tmp/requirements.txt


# ═══ Stage 2: Runtime ═══════════════════════════════════════════════════
FROM python:3.12-slim-bookworm AS runtime

# Sistem deps minime:
#   ffmpeg       — frame + audio extraction
#   libgl1       — OpenCV runtime
#   libglib2.0-0 — OpenCV glib runtime
#   libgles2     — MediaPipe OpenGL ES (libGLESv2.so.2)
#   libegl1      — MediaPipe EGL (libEGL.so.1)
#   libgomp1     — OpenMP
#   curl         — pentru healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends \
        ffmpeg \
        libgl1 \
        libglib2.0-0 \
        libgomp1 \
        libgles2 \
        libegl1 \
        curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Copiem venv-ul pre-construit
COPY --from=builder /opt/venv /opt/venv
ENV VIRTUAL_ENV=/opt/venv
ENV PATH="$VIRTUAL_ENV/bin:$PATH"

# Non-root user pentru securitate
RUN groupadd --system --gid 1001 app \
    && useradd --system --uid 1001 --gid app --create-home --home-dir /home/app app

WORKDIR /app

# ── Copiere cod (ordine: stabil → modificat des, pentru cache optim) ────

# 1. MediaPipe model (rar modificat, ~3.6 MB)
COPY --chown=app:app face_landmarker.task ./

# 2. Tools forensice (5 module)
COPY --chown=app:app tools/ ./tools/

# 3. Glue layer
COPY --chown=app:app forensic/ ./forensic/

# 4. Core API + preprocessing (cele mai des modificate)
COPY --chown=app:app api.py preprocessing.py ./
COPY --chown=app:app requirements.txt ./

# Directoare runtime
RUN mkdir -p /app/data/inference /app/data/results \
    && chown -R app:app /app

USER app

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    API_HOST=0.0.0.0 \
    API_PORT=8080

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
    CMD curl --fail --silent --max-time 5 http://localhost:8080/health || exit 1

CMD ["python", "api.py"]
