FROM python:3.12-slim

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    curl \
    libpango-1.0-0 \
    libpangoft2-1.0-0 \
    libgdk-pixbuf-2.0-0 \
    libffi-dev \
    shared-mime-info \
    libcairo2 \
    libgobject-2.0-0 \
    libmaxminddb0 \
    && rm -rf /var/lib/apt/lists/*

# Create app user
RUN useradd --create-home --shell /bin/bash app

# Set work directory
WORKDIR /app

# Copy requirements first for better caching
COPY requirements.txt .

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

# Copy application code
COPY . .

# Create uploads directory with proper permissions
RUN mkdir -p /app/uploads

# Create geoip directory for MaxMind GeoLite2-City database
# NOTE: The GeoLite2-City.mmdb binary file (~60MB) is NOT bundled in the image.
# It must be downloaded separately and mounted at runtime via Docker volume:
#   ./geoip/GeoLite2-City.mmdb:/app/geoip/GeoLite2-City.mmdb:ro
# Use scripts/download_geoip_db.sh to obtain the file (requires a free MaxMind account).
RUN mkdir -p /app/geoip
# Create data directory for MaxMind GeoIP database
RUN mkdir -p /app/data

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

# Switch to app 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

# Server command — no --reload to prevent file-watcher restart cycles on the
# mounted .:/app volume.  Use --reload locally by overriding CMD at docker run
# time or via a docker-compose.override.yml.
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]

# Production command (uncomment for production)
# CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
