# Stage 1: Build dependencies
FROM python:3.11-slim AS builder

RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc g++ libffi-dev && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /build
COPY pyproject.toml README.md ./
COPY skop_runner/ ./skop_runner/

# Install runner
RUN pip install --no-cache-dir .

# Pre-bake comprehensive Python package library
# Core data science + visualization
RUN pip install --no-cache-dir \
    numpy pandas scipy matplotlib seaborn scikit-learn statsmodels \
    plotly bokeh altair pillow

# ML (gradient boosting — no torch/tensorflow to keep image manageable)
RUN pip install --no-cache-dir \
    xgboost lightgbm catboost

# NLP + transformers
RUN pip install --no-cache-dir \
    nltk spacy transformers tokenizers sentencepiece

# Computer vision + image processing
RUN pip install --no-cache-dir \
    opencv-python-headless scikit-image

# Data formats, IO, databases, web
RUN pip install --no-cache-dir \
    openpyxl xlsxwriter pyarrow fastparquet h5py tables \
    sqlalchemy psycopg2-binary pymongo redis \
    requests httpx beautifulsoup4 lxml

# Geospatial
RUN pip install --no-cache-dir \
    geopandas shapely folium

# Time series + Bayesian
RUN pip install --no-cache-dir \
    prophet pmdarima statsforecast \
    pymc arviz

# Math, optimization, symbolic
RUN pip install --no-cache-dir \
    sympy cvxpy pulp

# Quantitative finance
RUN pip install --no-cache-dir \
    yfinance

# Computational biology
RUN pip install --no-cache-dir \
    biopython

# Network analysis + utilities
RUN pip install --no-cache-dir \
    networkx \
    tqdm joblib dask polars \
    numba \
    pydantic pyyaml jsonschema \
    ipywidgets nbconvert

# Stage 2: Runtime image
FROM python:3.11-slim

# Install minimal runtime deps (some native libs need shared objects)
RUN apt-get update && apt-get install -y --no-install-recommends \
    libgomp1 && \
    rm -rf /var/lib/apt/lists/*

# Copy installed packages from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Install uv for fast package management (cloud runners)
COPY --from=ghcr.io/astral-sh/uv:0.6 /uv /usr/local/bin/uv

# Create non-root user
RUN useradd -m -u 1000 appuser

# Copy demo project template
COPY templates/demo /templates/demo

# Set up workspace directory (will be a Fly volume mount point)
RUN mkdir -p /workspace && chown appuser:appuser /workspace

USER appuser
WORKDIR /workspace

# Runner reads config from env vars in cloud mode
ENV SKOP_CLOUD_RUNNER=true

CMD ["python", "-m", "skop_runner", "start"]
