# ============================================
# 🔨 Stage 1: BUILDER - Build Dependencies
# ============================================
FROM python:3.11-alpine AS builder

WORKDIR /app

# Install build dependencies for Alpine
RUN apk add --no-cache \
    gcc \
    g++ \
    musl-dev \
    linux-headers \
    postgresql-dev \
    libffi-dev \
    openssl-dev \
    cargo \
    rust

# Copy requirements
COPY requirements.txt .

# Install Python packages to /install directory
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# ============================================
# ✨ Stage 2: RUNTIME - SIÊU NHẸ với Alpine!
# ============================================
FROM python:3.11-alpine

WORKDIR /app

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PATH="/install/bin:$PATH" \
    PYTHONPATH="/install/lib/python3.11/site-packages"

# Install ONLY runtime dependencies (không build tools!)
RUN apk add --no-cache \
    curl \
    libpq \
    libgcc \
    libstdc++

# Copy installed packages from builder stage
COPY --from=builder /install /install

# Copy application code
COPY . .

# Set up entrypoint script
RUN chmod +x /app/entrypoint.sh

# Create data directory
RUN mkdir -p /app/data

# Expose port
EXPOSE 5000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:5000/docs || exit 1

# Run entrypoint script
CMD ["/app/entrypoint.sh"]