FROM python:3-slim

WORKDIR /app

# Install system dependencies (curl, sqlite3 for database, wget for healthcheck)
RUN apt-get update && apt-get install -y \
    curl \
    sqlite3 \
    wget \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .

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

# Copy application code
COPY . .

# Create required directories
RUN mkdir -p logs instance

ENV FLASK_APP=app.py
ENV PYTHONUNBUFFERED=1

# Add health check endpoint
RUN echo 'from flask import Blueprint\n\
health_bp = Blueprint("health", __name__)\n\
\n\
@health_bp.route("/health")\n\
def health_check():\n\
    return {"status": "healthy"}, 200\n'\
> /app/health.py

# Add the health blueprint to app.py if it doesn't exist
RUN grep -q "health_bp" app.py || sed -i '/from flask import/a from health import health_bp' app.py
RUN grep -q "app.register_blueprint(health_bp)" app.py || sed -i '/app = Flask/a app.register_blueprint(health_bp)' app.py

EXPOSE 5000

# Add startup script to initialize database if needed
RUN echo '#!/bin/bash\n\
if [ ! -f "instance/myp.db" ] || [ ! -s "instance/myp.db" ]; then\n\
    echo "Initializing database..."\n\
    python -c "from app import init_db; init_db()"\n\
fi\n\
\n\
echo "Starting gunicorn server..."\n\
gunicorn --bind 0.0.0.0:5000 app:app\n'\
> /app/start.sh && chmod +x /app/start.sh

CMD ["/app/start.sh"]