FROM --platform=linux/amd64 python:3.11-slim

# Set working directory
WORKDIR /app

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

# Install uv for faster package management
RUN pip install uv

# Copy dependency files
COPY pyproject.toml uv.lock ./

# Install Python dependencies
RUN uv sync --frozen --no-dev

# Copy application code
COPY . .

# Create directories for agent communication
RUN mkdir -p /tmp/agent_commands

# Expose the port
EXPOSE 8000

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

# Create startup script
COPY <<EOF /app/start.sh
#!/bin/bash
set -e

# Load environment variables from .env file if it exists
# Only set variables that are not already set
if [ -f .env ]; then
    echo "Loading environment variables from .env file..."
    set -a  # automatically export all variables
    source .env
    set +a  # stop auto-exporting
fi

# Run database migrations
echo "Running database migrations..."
uv run alembic upgrade head

# Start FastAPI server
if [ "\$APP_ENV" = "development" ]; then
    echo "Starting FastAPI development server..."
    exec uv run fastapi dev main.py --host 0.0.0.0 --port 8000
else
    echo "Starting FastAPI production server..."
    exec uv run uvicorn app.main:app --host 0.0.0.0 --port 8000
fi
EOF

RUN chmod +x /app/start.sh

# Default command
CMD ["/app/start.sh"]
