# Use amd64 platform for better Essentia compatibility, works with emulation on ARM
FROM --platform=linux/amd64 python:3.9-slim

# Install system dependencies
RUN apt-get update && apt-get install -y \
    ffmpeg \
    libsndfile1 \
    libsndfile1-dev \
    gcc \
    g++ \
    gfortran \
    libopenblas-dev \
    liblapack-dev \
    pkg-config \
    curl \
    build-essential \
    libyaml-dev \
    libfftw3-dev \
    libavcodec-dev \
    libavformat-dev \
    libavutil-dev \
    libswresample-dev \
    libsamplerate0-dev \
    libtag1-dev \
    libchromaprint-dev \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Upgrade pip, setuptools, wheel
RUN pip install --no-cache-dir --upgrade pip setuptools wheel

# Copy requirements
COPY backend/requirements.txt .

# Install Python dependencies in stages for better caching
# Using versions compatible with Python 3.9
RUN pip install --no-cache-dir numpy==1.24.3
RUN pip install --no-cache-dir scipy==1.11.4

# Install Essentia-TensorFlow - Python 3.9 AMD64 support
RUN pip install --no-cache-dir essentia-tensorflow

RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY backend/src/ ./src/
COPY backend/alembic.ini .

# Copy Essentia models into image (28 MB total)
COPY backend/models/ ./models/
RUN ls -lh /app/models

# Expose port
EXPOSE 8000

# Run migrations and start server
CMD alembic upgrade head && \
    uvicorn src.api.main:app --host 0.0.0.0 --port 8000
