# Multi-stage Dockerfile for WebDAV Server
# Optimized for production deployment

# ============================================================================
# Stage 1: Builder - Install dependencies and prepare environment
# ============================================================================
FROM python:3.11-slim as builder

# Set working directory
WORKDIR /build

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    g++ \
    libxml2-dev \
    libxslt-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements
COPY requirements.txt .

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


# ============================================================================
# Stage 2: Runtime - Create minimal production image
# ============================================================================
FROM python:3.11-slim

# Set labels for metadata
LABEL maintainer="WebDAV Server <webdav@example.com>"
LABEL description="Production-ready WebDAV Server with aiohttp"
LABEL version="1.0.0"

# Create app user for security (don't run as root)
RUN groupadd -r webdav && useradd -r -g webdav webdav

# Install runtime dependencies only
RUN apt-get update && apt-get install -y --no-install-recommends \
    libxml2 \
    libxslt1.1 \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy Python packages from builder
COPY --from=builder /install /usr/local

# Copy application files
COPY main.py .
COPY gunicorn_config.py .
COPY .env.example .env

# Create necessary directories
RUN mkdir -p /app/webdav /app/logs /app/backups && \
    chown -R webdav:webdav /app

# Switch to non-root user
USER webdav

# Expose port
EXPOSE 8080

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

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV HOST=0.0.0.0
ENV PORT=8080

# Run application
CMD ["python", "main.py"]
