FROM python:3.14-slim-bookworm as base

ENV PYTHONUNBUFFERED 1
WORKDIR /build

# Create requirements.txt file
FROM base as deps
RUN pip install uv==0.4.26
COPY pyproject.toml ./
RUN uv pip compile pyproject.toml -o /requirements.txt

FROM base as common
COPY --from=deps /requirements.txt .
# Create venv, add it to path and install requirements
RUN python -m venv /venv
ENV PATH="/venv/bin:$PATH"
RUN apt-get update \
     && apt-get install -y --no-install-recommends \
         curl \
         build-essential \
         libpq-dev \
         libffi-dev \
         python3-dev \
        && rm -rf /var/lib/apt/lists/*

# Ensure pip/setuptools/wheel and Rust toolchain helpers are up-to-date so
# binary wheels are preferred and building from source can succeed when needed.
# Upgrade pip and wheel tooling so prebuilt wheels are preferred
RUN pip install --upgrade pip setuptools wheel

# Install Python dependencies (will build wheels if prebuilt wheels are unavailable)
RUN pip install -r requirements.txt

# Install uvicorn server
RUN pip install uvicorn[standard]

# Copy the rest of app
COPY app app
COPY alembic alembic
COPY alembic.ini .
COPY pyproject.toml .
COPY init.sh .

# Create new user to run app process as unprivilaged user
RUN addgroup --gid 1001 --system uvicorn && \
    adduser --gid 1001 --shell /bin/false --disabled-password --uid 1001 uvicorn

# Run init.sh script then start uvicorn
RUN chown -R uvicorn:uvicorn /build
CMD bash init.sh && \
    runuser -u uvicorn -- /venv/bin/uvicorn app.main:app --app-dir /build --host 0.0.0.0 --port 8000 --workers 2 --loop uvloop
EXPOSE 8000