FROM python:3.12-slim

WORKDIR /app

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

# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY src/ ./src/

# Copy migrations
COPY migrations/ ./migrations/

# Expose port
EXPOSE 8001

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

# Create startup script that runs migrations then starts the app
RUN echo '#!/bin/bash\n\
echo "Running database migrations..."\n\
python migrations/migrate.py\n\
echo "Starting application..."\n\
exec uvicorn src.main:app --host 0.0.0.0 --port 8001' > /app/start.sh && \
chmod +x /app/start.sh

# Start with migration and then application
CMD ["/app/start.sh"]
