# TSU-WAVE Dockerfile
# Multi-stage build for optimized production image

# ========== STAGE 1: Builder ==========
FROM python:3.10-slim as builder

WORKDIR /build

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    gfortran \
    liblapack-dev \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements
COPY requirements.txt .
COPY requirements-dev.txt .

# Create virtual environment and install dependencies
RUN python -m venv /venv
ENV PATH="/venv/bin:$PATH"

RUN pip install --upgrade pip && \
    pip install --no-cache-dir wheel && \
    pip install --no-cache-dir -r requirements.txt && \
    pip install --no-cache-dir numpy && \
    if [ -f requirements-dev.txt ]; then pip install --no-cache-dir -r requirements-dev.txt; fi

# ========== STAGE 2: Fortran Compiler ==========
FROM python:3.10-slim as fortran-builder

WORKDIR /fortran-build

# Install Fortran compiler
RUN apt-get update && apt-get install -y --no-install-recommends \
    gfortran \
    liblapack-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy source and compile NSWE solver
COPY src/core/nswe_solver.f90 .
RUN python -c "import numpy; import numpy.f2py; numpy.f2py.main()" -c nswe_solver.f90 -m nswe_solver

# ========== STAGE 3: Final Image ==========
FROM python:3.10-slim

# Create tsu-wave user
RUN useradd --create-home --shell /bin/bash tsuwave

# Install runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    liblapack3 \
    libgfortran5 \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create directories
WORKDIR /app

# Copy virtual environment from builder
COPY --from=builder --chown=tsuwave:tsuwave /venv /venv
ENV PATH="/venv/bin:$PATH"

# Copy compiled Fortran module
COPY --from=fortran-builder --chown=tsuwave:tsuwave /fortran-build/nswe_solver.*.so /app/src/tsuwave/core/

# Copy application code
COPY --chown=tsuwave:tsuwave . .

# Create necessary directories with proper permissions
RUN mkdir -p /app/data /app/logs /app/config && \
    chown -R tsuwave:tsuwave /app

# Switch to non-root user
USER tsuwave

# Expose ports
EXPOSE 8000 8080

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

# Set environment variables
ENV PYTHONPATH=/app/src
ENV TSUWAVE_ENV=production
ENV TSUWAVE_CONFIG=/app/config/config.yml

# Default command
CMD ["uvicorn", "tsuwave.api.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]

# Alternative commands:
# CMD ["streamlit", "run", "src/tsuwave/dashboard/app.py", "--server.port=8080", "--server.address=0.0.0.0"]
# CMD ["python", "src/main.py"]
