# ============================================
# BraceIQMed Brace Generator - FastAPI + PyTorch (CPU)
# Build context: repo root (braceiqmed/)
# ============================================

FROM python:3.10-slim

# Prevent interactive prompts
ENV DEBIAN_FRONTEND=noninteractive

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libgl1 \
    libglib2.0-0 \
    libsm6 \
    libxext6 \
    libxrender-dev \
    wget \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Install PyTorch CPU version (smaller, no CUDA)
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir torch torchvision --index-url https://download.pytorch.org/whl/cpu

# Copy and install requirements
COPY brace-generator/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Copy scoliovis-api requirements and install
COPY scoliovis-api/requirements.txt /app/requirements-scoliovis.txt
RUN pip install --no-cache-dir -r requirements-scoliovis.txt || true

# Create brace_generator package structure
RUN mkdir -p /app/brace_generator

# Copy brace-generator code as a package
COPY brace-generator/*.py /app/brace_generator/
COPY brace-generator/__init__.py /app/brace_generator/__init__.py

# Also keep server_DEV structure for compatibility
RUN mkdir -p /app/brace_generator/server_DEV
COPY brace-generator/*.py /app/brace_generator/server_DEV/

# Copy scoliovis-api
COPY scoliovis-api/ /app/scoliovis-api/

# Copy templates
COPY templates/ /app/templates/

# Set Python path - include both locations
ENV PYTHONPATH=/app:/app/scoliovis-api

# Environment variables
ENV HOST=0.0.0.0
ENV PORT=8002
ENV DEVICE=cpu
ENV MODEL=scoliovis
ENV TEMP_DIR=/tmp/brace_generator
ENV CORS_ORIGINS=*

# Create directories
RUN mkdir -p /tmp/brace_generator /app/data/uploads /app/data/outputs

EXPOSE 8002

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

# Run the server from the brace_generator package
CMD ["python", "-m", "uvicorn", "brace_generator.server_DEV.app:app", "--host", "0.0.0.0", "--port", "8002"]
