
FROM docker.io/python:3.12.9-slim-bookworm AS python-build-stage

ARG BUILD_ENVIRONMENT=local

# Instalar apenas dependências para construir pacotes Python
RUN apt-get update && apt-get install --no-install-recommends -y \
    build-essential \
    libpq-dev \
    # libtesseract-dev pode ser necessário aqui se alguma lib Python compila contra ele
    libtesseract-dev \
 && rm -rf /var/lib/apt/lists/*

# Requirements são instalados aqui para garantir que serão cacheados.
COPY ./requirements .

# Criar Wheels das dependências Python.
RUN pip wheel --wheel-dir /usr/src/app/wheels  \
    -r ${BUILD_ENVIRONMENT}.txt


# Python 'run' stage - ESTA É A IMAGEM FINAL
FROM docker.io/python:3.12.9-slim-bookworm AS python-run-stage

ARG BUILD_ENVIRONMENT=local
ARG APP_HOME=/app

ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV BUILD_ENV=${BUILD_ENVIRONMENT}

WORKDIR ${APP_HOME}

# Instalar TODAS as dependências de sistema necessárias em TEMPO DE EXECUÇÃO
RUN apt-get update && apt-get install --no-install-recommends -y \
    # Dependências do psycopg e outras utilidades
    libpq-dev \
    wait-for-it \
    gettext \
    poppler-utils \
    unpaper \
    tesseract-ocr \
    tesseract-ocr-por \
    ghostscript \
    openjdk-17-jdk \
    # libtesseract-dev \
    # Utilitários do devcontainer e outros
    sudo git bash-completion vim ssh curl \
 # Limpeza
 && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
 && rm -rf /var/lib/apt/lists/*

# Criar usuário devcontainer (manter como está)
RUN groupadd --gid 1000 dev-user \
    && useradd --uid 1000 --gid dev-user --shell /bin/bash --create-home dev-user \
    && echo dev-user ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/dev-user \
    && chmod 0440 /etc/sudoers.d/dev-user

# Instalar dependências Python a partir dos wheels (manter como está)
COPY --from=python-build-stage /usr/src/app/wheels  /wheels/
RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \
    && rm -rf /wheels/

# Copiar scripts e código (manter como está)
COPY ./compose/production/django/entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint
COPY ./compose/local/django/start /start
RUN sed -i 's/\r$//g' /start
RUN chmod +x /start
COPY . ${APP_HOME}

# REMOVER esta linha, poppler-utils já foi instalado acima
# RUN apt-get update && apt-get install -y poppler-utils

ENTRYPOINT ["/entrypoint"]

