FROM python:3.12-slim

WORKDIR /app

# Install system dependencies including Playwright requirements
RUN apt-get update && apt-get install -y \
    gcc \
    postgresql-client \
    wget \
    && rm -rf /var/lib/apt/lists/*

# Copy dependency specification first for better layer caching
COPY pyproject.toml ./

# Copy application packages (needed before pip install)
COPY packages/ ./packages/
COPY apps/ ./apps/
COPY infrastructure/alembic/ ./infrastructure/alembic/
COPY infrastructure/alembic.ini ./infrastructure/
COPY infrastructure/scripts/ ./infrastructure/scripts/

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

# Install Playwright browsers (Chromium only for web scraping)
RUN playwright install --with-deps chromium

# Create necessary directories
RUN mkdir -p /app/reports /app/.cache

# Verify web UI files are present
RUN ls -la /app/apps/backend/web/templates/ && ls -la /app/apps/backend/web/static/

# Set PYTHONPATH to ensure modules are found
ENV PYTHONPATH=/app:$PYTHONPATH

# Expose API port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import requests; requests.get('http://localhost:8000/health', timeout=5)" || exit 1

# Run API server
CMD ["uvicorn", "apps.backend.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
