# Dockerfile for PowerOn Gateway - Google Cloud Run
# Python 3.11 base image optimized for Cloud Run

FROM python:3.11-slim

# Set working directory
WORKDIR /app

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    NUMEXPR_MAX_THREADS=12 \
    PORT=8000

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    postgresql-client \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements first for better caching (requirements.lock from "Update requirements.lock" workflow)
COPY requirements.txt .
COPY requirements.lock .

# Install Python dependencies (lock file avoids slow pip backtracking)
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.lock

# Copy application code (includes .env file created by workflow from env_gcp.env)
COPY . .

# Create directories for logs (Cloud Run uses /tmp for writable storage)
RUN mkdir -p /tmp/logs /tmp/debug

# Note: .env file (created from env_gcp.env by workflow) contains encrypted secrets
# These are decrypted at runtime using the master key from Secret Manager
# (mounted as CONFIG_KEY environment variable in Cloud Run)

# Expose port (Cloud Run sets PORT env var, but we default to 8000)
EXPOSE 8000

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

# Run the application
# Cloud Run will set PORT env var, uvicorn reads it automatically
CMD exec uvicorn app:app --host 0.0.0.0 --port ${PORT:-8000} --workers 1
