# syntax=docker/dockerfile:1

# ---- build stage: resolve and install the Python dependencies into a venv ----
FROM python:3.12-slim AS builder

ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

WORKDIR /build
COPY pyproject.toml ./
COPY app ./app
# Install the dependencies only. The application itself runs from /srv/app, so the
# copy pip just installed into site-packages is removed to avoid a shadow copy.
RUN pip install . && pip uninstall -y pharma-field-force

# ---- runtime stage ----
FROM python:3.12-slim

# WeasyPrint's native libraries and the fonts the PDF forms name: Liberation Sans/Serif
# (metric-compatible with the Arial/Times of the printed company forms), Carlito (the
# Calibri look-alike) and DejaVu as the last-resort fallback.
# Pinned here so a missing library shows up at build time, not at the first PDF.
RUN apt-get update && apt-get install -y --no-install-recommends \
        libpango-1.0-0 \
        libpangoft2-1.0-0 \
        libharfbuzz0b \
        fontconfig \
        fonts-dejavu-core \
        fonts-liberation \
        fonts-crosextra-carlito \
        curl \
    && rm -rf /var/lib/apt/lists/*

ENV PATH="/opt/venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    ENVIRONMENT=production \
    PDF_STORAGE_PATH=/srv/storage/pdf \
    WEB_CONCURRENCY=2

COPY --from=builder /opt/venv /opt/venv

WORKDIR /srv
COPY app ./app
COPY alembic ./alembic
COPY alembic.ini ./
COPY scripts ./scripts

RUN useradd --create-home --uid 1000 appuser \
    && mkdir -p /srv/storage/pdf \
    && chown -R appuser:appuser /srv/storage \
    && chmod +x /srv/scripts/docker-entrypoint.sh
USER appuser

# Fail the image build if the PDF engine cannot load (missing system library).
RUN python -c "import weasyprint; weasyprint.HTML(string='<p>ok</p>').write_pdf()"

EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
    CMD curl -fsS http://localhost:8000/health || exit 1

ENTRYPOINT ["/srv/scripts/docker-entrypoint.sh"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", \
     "--proxy-headers", "--forwarded-allow-ips", "*"]
