FROM python:3.12-slim

LABEL maintainer="BalanceBoard"
LABEL description="BalanceBoard - Content aggregation platform with ethical design"

# Install system dependencies
RUN apt-get update && apt-get install -y \
    postgresql-client \
    libpq-dev \
    gcc \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user for security
RUN useradd -m -u 1000 appuser && \
    mkdir -p /app && \
    chown -R appuser:appuser /app

# Set working directory
WORKDIR /app

# Copy requirements first for better caching
COPY --chown=appuser:appuser requirements.txt .

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

# Copy application code
COPY --chown=appuser:appuser . .

# Create necessary directories with proper permissions
RUN mkdir -p \
    /app/data/posts \
    /app/data/comments \
    /app/data/moderation \
    /app/static/avatars \
    /app/backups \
    && chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Expose Flask port
EXPOSE 5021

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

# Set Flask app environment variable
ENV FLASK_APP=app:create_app

# Run the application directly with Flask
# Note: start_server.py has venv checks that don't apply in Docker
CMD ["python", "-m", "flask", "--app", "app:create_app", "run", "--host=0.0.0.0", "--port=5021"]
