FROM python:3.11-slim

# Install required system dependencies
RUN apt-get update && apt-get install -y \
    wget \
    gnupg2 \
    procps \
    sqlite3 \
    fonts-ipafont-gothic \
    fonts-wqy-zenhei \
    fonts-thai-tlwg \
    fonts-kacst \
    fonts-freefont-ttf \
    libxss1 \
    xvfb \
    --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy requirements first to leverage Docker cache
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Install Playwright system dependencies as root
RUN playwright install-deps chromium

# Create a non-root user
RUN useradd -m playwright

# Set HOME for playwright user and ensure cache directory exists
ENV HOME=/home/playwright
RUN mkdir -p /home/playwright/.cache/ms-playwright && chown -R playwright:playwright /home/playwright

# Install Playwright browsers as the playwright user
USER playwright
RUN playwright install chromium

# Switch back to root for file operations
USER root

# Copy the rest of the application
COPY . .

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV API_KEY=""
ENV CACHE_EXPIRY_HOURS=36
ENV CLEANUP_CRON="0 3 * * *"

# Set ownership of the application to playwright user
RUN chown -R playwright:playwright /app

# Create the database directory and set permissions
RUN mkdir -p /db && chmod 777 /db && chown -R playwright:playwright /app

# Add system limits configuration
RUN echo "* soft nofile 65535" >> /etc/security/limits.conf && \
    echo "* hard nofile 65535" >> /etc/security/limits.conf && \
    echo "session required pam_limits.so" >> /etc/pam.d/common-session

# Switch to playwright user for running the application
USER playwright

# Expose port
EXPOSE 8000

# Run the application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
