# Radiolink M2R
# Build dependencies stay in the builder stage; the Raspberry Pi receives only
# the runtime libraries and the ready-to-run Python environment.
FROM python:3.12-slim AS builder

ARG ENABLE_GPIO=0

ENV DEBIAN_FRONTEND=noninteractive
ENV PATH=/opt/venv/bin:$PATH

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    python3-dev \
    libasound2-dev \
    portaudio19-dev \
    pkg-config \
    libffi-dev \
    libssl-dev \
    libgpiod-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build

COPY requirements.txt /build/requirements.txt
COPY pymumble2 /build/pymumble2

RUN python -m venv /opt/venv \
    && python -m pip install --upgrade pip "setuptools<81" wheel \
    && pip install --no-cache-dir numpy webrtcvad \
    && pip install --no-cache-dir ./pymumble2 \
    && pip install --no-cache-dir -r requirements.txt \
    && if [ "$ENABLE_GPIO" = "1" ]; then pip install --no-cache-dir gpiod; fi \
    && pip install --no-cache-dir pyaudio \
    && python -c "import importlib.metadata; print('pymumble build-time version:', importlib.metadata.version('pymumble'))"


FROM python:3.12-slim AS runtime

ARG ENABLE_GPIO=0

ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHONUNBUFFERED=1
ENV PATH=/opt/venv/bin:$PATH

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        alsa-utils \
        ca-certificates \
        ffmpeg \
        libasound2 \
        libopus0 \
        libportaudio2 \
        openssl \
    && if [ "$ENABLE_GPIO" = "1" ]; then apt-get install -y --no-install-recommends libgpiod3; fi \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

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

RUN chmod +x /app/docker-entrypoint.sh \
    && python -c "import mumble, pyaudio, yaml; print('M2R runtime imports OK')"

ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["python3", "-m", "src.main"]
