FROM python:3.12-slim AS builder

ENV POETRY_VERSION=1.8.4 \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    PIP_NO_CACHE_DIR=1

# `pip install` puts poetry on PATH (/usr/local/bin/poetry) — don't bother
# with POETRY_HOME indirection.
RUN pip install --no-cache-dir "poetry==${POETRY_VERSION}"

WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN poetry install --only main --no-root

COPY broker_sync ./broker_sync
RUN poetry install --only main


FROM python:3.12-slim

WORKDIR /app

# Playwright needs a big list of system libs for Chromium (fonts, NSS, libs
# for rendering, audio stubs, etc.). Mirror the list Playwright publishes at
# https://playwright.dev/docs/browsers#system-requirements for Debian 12.
# Fidelity PlanViewer is the only consumer today; gated to the fidelity-*
# CronJobs via the provider's explicit Playwright import.
RUN apt-get update && apt-get install --no-install-recommends -y \
      ca-certificates \
      fonts-liberation \
      fonts-noto-color-emoji \
      libasound2 \
      libatk-bridge2.0-0 \
      libatk1.0-0 \
      libatspi2.0-0 \
      libcairo2 \
      libcups2 \
      libdbus-1-3 \
      libdrm2 \
      libexpat1 \
      libgbm1 \
      libglib2.0-0 \
      libnspr4 \
      libnss3 \
      libpango-1.0-0 \
      libx11-6 \
      libxcb1 \
      libxcomposite1 \
      libxdamage1 \
      libxext6 \
      libxfixes3 \
      libxkbcommon0 \
      libxrandr2 \
      xvfb \
    && rm -rf /var/lib/apt/lists/*

RUN useradd --system --uid 10001 --home /app --shell /usr/sbin/nologin broker && \
    mkdir -p /data && chown -R broker:broker /data

COPY --from=builder --chown=broker:broker /app /app

# Install Chromium into broker's cache so Playwright (running as broker)
# can pick it up. `PLAYWRIGHT_BROWSERS_PATH=0` forces a co-located install
# next to the python package — the simpler path on slim images.
ENV PATH="/app/.venv/bin:${PATH}" \
    PYTHONUNBUFFERED=1 \
    PLAYWRIGHT_BROWSERS_PATH=/app/.playwright-browsers
RUN mkdir -p "${PLAYWRIGHT_BROWSERS_PATH}" && \
    chown -R broker:broker "${PLAYWRIGHT_BROWSERS_PATH}"

USER broker
RUN playwright install chromium

ENTRYPOINT ["broker-sync"]
CMD ["version"]
