FROM python:3.14-alpine AS builder

LABEL org.opencontainers.image.source=https://github.com/zhrif/maybankforme
LABEL org.opencontainers.image.description="FastAPI service to process Maybank CC statement PDF files to CSV"

WORKDIR /build

# Install build dependencies
RUN apk add --no-cache git

# Copy only dependency files first for better caching
COPY requirements.txt pyproject.toml /build/
COPY .git /build/.git

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy source code
COPY src /build/src

# Install the package
RUN pip install --no-cache-dir -e .

# Production stage
FROM python:3.14-alpine

LABEL org.opencontainers.image.source=https://github.com/zhrif/maybankforme
LABEL org.opencontainers.image.description="FastAPI service to process Maybank CC statement PDF files to CSV"

WORKDIR /app

# Create non-root user
RUN addgroup -g 1000 appuser && \
    adduser -D -u 1000 -G appuser appuser && \
    mkdir -p /app /tmp/maybankforme && \
    chown -R appuser:appuser /app /tmp/maybankforme

# Copy installed packages from builder
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 source code
COPY --from=builder /build/src /app/src

# Switch to non-root user
USER appuser

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    LOG_LEVEL=INFO \
    LOG_FORMAT=json \
    IN_CONTAINER=true \
    PORT=8000 \
    PYTHONPATH=/app/src

EXPOSE 8000

# Add healthcheck
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1

CMD ["python", "-m", "maybankforme.server"]
