FROM python:3.12-slim-bookworm@sha256:0f5b26b9518d002b6173fd61daad821fa340635ebfec5bba471013f9ca114579 AS base

# Install system dependencies
RUN apt-get update && \
    apt-get install --no-install-recommends -y build-essential git libportaudio2 pandoc && \
    rm -rf /var/lib/apt/lists/*

# Create app user with UID 1000
RUN useradd -m -u 1000 -s /bin/bash appuser

WORKDIR /app

# Create virtual environment
RUN python -m venv /venv
ENV PATH="/venv/bin:$PATH"

# Playwright browser settings
ENV PLAYWRIGHT_BROWSERS_PATH=/home/appuser/pw-browsers
ENV PLAYWRIGHT_SKIP_BROWSER_GC=1

# Create directories with proper permissions
RUN mkdir -p /home/appuser/.patch /home/appuser/.cache /home/appuser/pw-browsers && \
    chown -R appuser:appuser /home/appuser /app

# So git doesn't complain about unusual permissions
RUN git config --system --add safe.directory /app

# HOME must NOT be /app. /app is WORKDIR and the directory users bind-mount their
# project into, and the whole repository-trust boundary is a comparison against
# Path.home(): with HOME=/app the repository's own .patch.conf.yml and .env are
# indistinguishable from the user's, so every filter in patch/main.py is inert
# and a cloned repo can set test-cmd and *_API_BASE. It also put the diskcache
# tags store -- whose values are unpickled -- back inside the repo under edit.
# Mount a volume at /home/appuser/.patch if the caches need to outlive the
# container.
ENV HOME=/home/appuser

#########################
FROM base AS patch-full

ENV PATCH_DOCKER_IMAGE=pierrunoyt/patch-full

COPY . /tmp/patch

# Install dependencies as root
RUN /venv/bin/python -m pip install --upgrade --no-cache-dir pip && \
    /venv/bin/python -m pip install --no-cache-dir /tmp/patch[browser,playwright] boto3 && \
    rm -rf /tmp/patch

# Install playwright browsers
RUN /venv/bin/python -m playwright install --with-deps chromium

# Switch to appuser
USER appuser

ENTRYPOINT ["/venv/bin/patch"]

#########################
FROM base AS patch

ENV PATCH_DOCKER_IMAGE=pierrunoyt/patch

COPY . /tmp/patch

# Install dependencies as root
RUN /venv/bin/python -m pip install --upgrade --no-cache-dir pip && \
    /venv/bin/python -m pip install --no-cache-dir \
       /tmp/patch[playwright] boto3 google-cloud-aiplatform && \
    rm -rf /tmp/patch

# Install playwright browsers
RUN /venv/bin/python -m playwright install --with-deps chromium

# Switch to appuser
USER appuser

ENTRYPOINT ["/venv/bin/patch"]
