# syntax=docker/dockerfile:1

# ---- Stage 1: build the SPA (Node exists ONLY here — react.md) --------
FROM node:22-slim AS frontend
WORKDIR /build
COPY frontend/package.json frontend/package-lock.json* ./
RUN if [ -f package-lock.json ]; then npm ci; else npm install; fi
COPY frontend/ ./
RUN npm run build

# ---- Stage 2: the app — one Python process -----------------------------
FROM python:3.12-slim

# postgresql-client-17 from PGDG. Load-bearing: the Supabase source is
# PG 17.x and the nightly snapshot's pg_dump runs IN this container and
# must match the server's major version (host pg_dump is v16).
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates curl gnupg \
 && curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
      | gpg --dearmor -o /usr/share/keyrings/pgdg.gpg \
 && . /etc/os-release \
 && echo "deb [signed-by=/usr/share/keyrings/pgdg.gpg] http://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
      > /etc/apt/sources.list.d/pgdg.list \
 && apt-get update \
 && apt-get install -y --no-install-recommends postgresql-client-17 \
 && apt-get purge -y curl gnupg \
 && apt-get autoremove -y \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# CHANGELOG.md is optional at build time (glob) — /api/meta degrades to null.
COPY alembic.ini CHANGELOG.md* ./
COPY alembic/ alembic/
COPY app/ app/
COPY scripts/ scripts/
COPY --from=frontend /build/dist frontend/dist/

EXPOSE 3000
CMD ["sh", "-c", "alembic upgrade head && exec uvicorn app.main:app --host 0.0.0.0 --port 3000"]
