# Two stages: build the SPA with Node (build-time only), then a slim Python image
# that serves both the API and the pre-built static SPA. Node is absent at runtime.

# --- 1. build the frontend -------------------------------------------------
FROM node:20-alpine AS frontend
WORKDIR /build
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci || npm install
COPY frontend/ ./
# vite build writes to ../app/static (see vite.config.ts); emit it under /out here.
RUN npm run build && mkdir -p /out && cp -r ../app/static /out/static

# --- 2. runtime ------------------------------------------------------------
FROM python:3.12-slim AS runtime
WORKDIR /app_root
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1

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

COPY app/ ./app/
COPY --from=frontend /out/static ./app/static

# Data dir for the SQLite accounts store; mount a volume here so it survives
# redeploys (the workspace `data/` dir).
ENV APP_DATA_DIR=/data
RUN mkdir -p /data

# Bind to all interfaces INSIDE the container; the gateway maps the published port
# to 172.17.0.1 on the host, so Caddy (and only Caddy) can reach it.
EXPOSE 3000
COPY alembic.ini ./
COPY alembic/ alembic/

# Migrations run at container start, then the server. `exec` so uvicorn is PID 1.
CMD ["sh", "-c", "alembic upgrade head && exec uvicorn app.main:app --host 0.0.0.0 --port 3000"]
