# --- Base image ---
FROM python:3.12-slim

# --- Environment variables ---
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# --- Set working directory ---
WORKDIR /cost-assistant

# --- Install system dependencies (cached until packages change) ---
RUN apt-get update && apt-get install -y --no-install-recommends \
    libgl1 \
    libglib2.0-0 \
    poppler-utils \
    curl \
    && rm -rf /var/lib/apt/lists/*

# --- Install Python dependencies (cached until requirements.txt changes) ---
COPY requirements.txt .
RUN python -m pip install --no-cache-dir -r requirements.txt

# --- Create user early (cached, rarely changes) ---
RUN groupadd -r appuser && useradd -r -g appuser appuser

# --- Copy only necessary application files ---
COPY --chown=appuser:appuser main.py .
COPY --chown=appuser:appuser cost_calculator.py .
COPY --chown=appuser:appuser mailer.py .
COPY --chown=appuser:appuser templates/ ./templates/
COPY --chown=appuser:appuser static/ ./static/

# --- Create upload folder ---
RUN mkdir -p data/uploads && chown -R appuser:appuser data/uploads

# --- Switch to non-root user for security ---
USER appuser

# --- Expose internal port ---
EXPOSE 8000

# --- Run Gunicorn with Uvicorn worker for production ---
CMD ["gunicorn", "main:app", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000", "--workers", "4", "--timeout", "120"]
