# syntax=docker/dockerfile:1

# =============================================================================
# LeoCRM v1.0 - Production Dockerfile
# Multi-stage build: frontend (Node) + builder (Python) + runtime (slim)
# =============================================================================

# === Stage 0: Frontend Build ===
FROM node:20-slim AS frontend

WORKDIR /frontend

# Copy package files first for layer caching
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci --silent 2>/dev/null || npm install --silent

# Copy frontend source and build
COPY frontend/ ./
RUN npx vite build

# === Stage 1: Python Builder ===
FROM python:3.12-slim AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
        build-essential \
        libpq-dev \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app

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

# === Stage 2: Runtime ===
FROM python:3.12-slim AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PATH=/home/appuser/.local/bin:$PATH

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
        libpq5 \
        curl \
 && rm -rf /var/lib/apt/lists/* \
 && groupadd -g 1000 appuser \
 && useradd -m -u 1000 -g appuser appuser

WORKDIR /app

# Copy installed Python packages from builder
COPY --from=builder /root/.local /home/appuser/.local

# Copy application source
COPY --chown=appuser:appuser . .

# Copy built frontend from frontend stage
COPY --from=frontend --chown=appuser:appuser /frontend/dist /app/frontend/dist

# Make prestart.sh executable
RUN chmod +x /app/prestart.sh

# Create storage directory
RUN mkdir -p /data/storage && chown -R appuser:appuser /data

USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
    CMD curl -fsS http://localhost:8000/api/v1/health || exit 1

ENTRYPOINT ["/app/prestart.sh"]
