# Multi-stage build: builder installs dependencies into a target dir,
# runtime copies only what's needed — keeps the final image smaller
# and avoids shipping build toolchains (gcc, headers) that some
# dependency wheels may need to compile against on platforms without
# prebuilt wheels.

# ---- Builder ----------------------------------------------------------------
FROM python:3.12-slim AS builder

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

COPY pyproject.toml ./
COPY src/ ./src/

RUN pip install --no-cache-dir --target=/build/deps .

# ---- Runtime ------------------------------------------------------------------
FROM python:3.12-slim AS runtime

# Playwright's headless Chromium (used by report/pdf_exporter.py) needs
# these OS libraries — without them, PDF report generation fails at
# runtime with an opaque "cannot open shared object file" error rather
# than at image-build time, so they're installed here rather than
# deferred to first use.
RUN apt-get update && apt-get install -y --no-install-recommends \
        libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 \
        libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2 \
        libpango-1.0-0 libcairo2 ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Real, non-root user — running an internet-facing API as root inside
# the container is an avoidable risk, not a convenience worth keeping.
RUN useradd --create-home --uid 1000 meridian

WORKDIR /app
COPY --from=builder /build/deps /usr/local/lib/python3.12/site-packages
COPY src/ ./src/

ENV PYTHONPATH=/app/src
ENV MERIDIAN_HOME=/data
ENV PYTHONUNBUFFERED=1

# Chromium for PDF report generation — see report/pdf_exporter.py,
# which reuses this same Playwright pattern from the legacy
# artifact_factory.py.
#
# Real bug caught by tracing through at build time, not assumed safe:
# `playwright install` runs here as root (before USER meridian below),
# and its DEFAULT install location is under root's home directory
# (~/.cache/ms-playwright), which the non-root meridian user cannot
# read at runtime — /root itself isn't world-traversable. Fixed by
# installing to an explicit, shared, world-readable path instead.
ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright-browsers
RUN python -m playwright install chromium \
    && chmod -R o+rX /opt/playwright-browsers

RUN mkdir -p /data && chown meridian:meridian /data
VOLUME ["/data"]

USER meridian
EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health', timeout=3).status == 200 else 1)" || exit 1

ENTRYPOINT ["python", "-m", "meridian.docker_entrypoint"]
CMD ["api"]
