# Multi-stage build for smaller image size
FROM python:3.14-alpine AS python-base

# Install runtime dependencies
RUN apk add --no-cache curl

# Create non-root user for security
RUN addgroup -g 1001 -S app &&\
    adduser -u 1001 -S app -G app

# Set working directory
WORKDIR /app

#############################################
# Builder stage
#############################################
FROM python-base AS builder

# Install build dependencies needed for cryptography
RUN apk add --no-cache gcc musl-dev libffi-dev openssl-dev

# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

#############################################
# Final stage
#############################################
FROM python-base

# Copy installed Python packages and binaries from builder stage
COPY --from=builder /usr/local/lib/python3.14/site-packages /usr/local/lib/python3.14/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy application files
COPY main.py .
COPY templates/ templates/

# Change ownership to non-root user
RUN chown -R app:app /app

# Switch to non-root user
USER app

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]