# Multi-stage Dockerfile for BDFR Web Interface with full BDFR backend support
# This image contains both the web interface and the complete BDFR tool

FROM python:3.11-slim AS builder

# Set working directory
WORKDIR /build

# Install build dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    git \
    && rm -rf /var/lib/apt/lists/*

# Copy BDFR source files and install it
COPY pyproject.toml ./
COPY bdfr/ ./bdfr/
RUN pip install --no-cache-dir .

# Copy and install web interface requirements
COPY web_interface/requirements.txt ./web_requirements.txt
RUN pip install --no-cache-dir -r web_requirements.txt


# Final stage - minimal runtime image
FROM python:3.11-slim

# Set labels
LABEL maintainer="BDFR Web Interface"
LABEL description="Complete BDFR with Web Interface - Download Reddit content via CLI or Web UI"
LABEL version="1.0.0"

# Set working directory
WORKDIR /app

# Install runtime dependencies (ffmpeg for video processing, curl for health checks)
RUN apt-get update && apt-get install -y \
    ffmpeg \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy Python packages from builder (installed globally in /usr/local)
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy web interface files
COPY web_interface/app/ ./app/
COPY web_interface/templates/ ./templates/
COPY web_interface/static/ ./static/
COPY web_interface/start.py ./start.py

# Copy entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Create necessary directories with proper permissions
RUN mkdir -p /downloads /app/data /app/logs && \
    chmod 755 /downloads /app/data /app/logs

# Create a non-root user for running the application
RUN useradd --create-home --shell /bin/bash bdfr && \
    chown -R bdfr:bdfr /app /downloads

# Switch to non-root user
USER bdfr

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV BDFR_DOWNLOAD_DIR=/downloads
ENV BDFR_DATA_DIR=/app/data
ENV BDFR_CONFIG_DIR=/app/data/bdfr-config
ENV APPDATA=/app/data/bdfr-config
ENV XDG_CONFIG_HOME=/app/data/bdfr-config

# Expose port for web interface
EXPOSE 8000

# Health check - verify web interface is responding
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Set entrypoint to handle runtime directory creation
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]

# Default command - start web interface
# Users can override this to run BDFR CLI commands
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]