# ---- Stage 1: Build frontend and wokwi-libs ----
FROM node:20 AS frontend-builder

WORKDIR /app

# Clone wokwi-libs fresh from upstream to avoid stale submodule pointers.
# git is pre-installed in the node:20 Debian image.
RUN git clone --depth=1 https://github.com/wokwi/avr8js.git wokwi-libs/avr8js \
 && git clone --depth=1 https://github.com/wokwi/rp2040js.git wokwi-libs/rp2040js \
 && git clone --depth=1 https://github.com/wokwi/wokwi-elements.git wokwi-libs/wokwi-elements

# Build avr8js
WORKDIR /app/wokwi-libs/avr8js
RUN npm install && npm run build --if-present

# Build rp2040js (may have no build script on some commits)
WORKDIR /app/wokwi-libs/rp2040js
RUN npm install && npm run build --if-present

# Build wokwi-elements
WORKDIR /app/wokwi-libs/wokwi-elements
RUN npm install && npm run build --if-present

# Build frontend
# components-metadata.json is already committed; skip generate:metadata
# (it requires wokwi-elements/src which isn't needed at runtime)
WORKDIR /app
COPY frontend/ frontend/
WORKDIR /app/frontend
RUN npm install && npm run build:docker


# ---- Stage 2: Final Production Image ----
FROM python:3.12-slim

# Install system dependencies and nginx
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
    nginx \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install arduino-cli into /usr/local/bin directly (avoids touching /bin)
RUN curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh \
    | BINDIR=/usr/local/bin sh

# Initialize arduino-cli config, add RP2040 board manager URL, then install cores
RUN arduino-cli config init \
    && arduino-cli config add board_manager.additional_urls \
       https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json \
    && arduino-cli core update-index \
    && arduino-cli core install arduino:avr \
    && arduino-cli core install rp2040:rp2040

WORKDIR /app

# Data directory for persistent SQLite database (mounted as a volume at runtime)
RUN mkdir -p /app/data

# Install Python backend dependencies
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy backend application code
COPY backend/app/ ./app/

# Setup Nginx configuration
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf

# Copy built frontend assets from builder stage
COPY --from=frontend-builder /app/frontend/dist /usr/share/nginx/html

# Copy and configure entrypoint script
COPY deploy/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

EXPOSE 80

CMD ["/app/entrypoint.sh"]
