# =============================================================================
# Stage 1: Frontend build
# =============================================================================
FROM node:20-alpine AS frontend-build

WORKDIR /build

COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci || npm install

COPY frontend/ ./
RUN npm run build

# =============================================================================
# Stage 2: Python API runtime
# =============================================================================
FROM python:3.12-slim AS api

WORKDIR /app

# Install system dependencies for psycopg2 and general use
RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc libpq-dev curl && \
    rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY backend/requirements.txt /app/backend/requirements.txt
RUN pip install --no-cache-dir -r /app/backend/requirements.txt

# Copy backend source
COPY backend/ /app/backend/
COPY alembic/ /app/alembic/
COPY alembic.ini /app/alembic.ini

# Copy frontend build for single-container mode
COPY --from=frontend-build /build/dist /app/static

# Create data directory for SQLite mode
RUN mkdir -p /data

ENV PYTHONPATH=/app/backend
ENV DATA_DIR=/data

# Entrypoint runs migrations then starts the app
COPY docker/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

EXPOSE 8000 8401

# Default: run migrations then start the API server
ENTRYPOINT ["/app/entrypoint.sh"]

# =============================================================================
# Stage 3: Nginx frontend (production compose)
# =============================================================================
FROM nginx:1.27-alpine AS web

# Remove default config
RUN rm /etc/nginx/conf.d/default.conf

# Copy custom nginx config
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf

# Copy built frontend assets
COPY --from=frontend-build /build/dist /usr/share/nginx/html

EXPOSE 80
