# PocketTrainer web flasher
#   docker compose up -d --build     ->  http://localhost:8080
# Stage 1 compiles both firmwares with PlatformIO, stage 2 fetches ESP Web Tools,
# stage 3 serves the static page + firmware with nginx.

# --- 1. Firmware ---------------------------------------------------------------
FROM python:3.11-slim AS firmware
RUN pip install --no-cache-dir platformio==6.2.0
WORKDIR /build
# toolchains first, so they stay cached when only the sources change
COPY platformio.ini ./
RUN mkdir -p src && echo 'void setup(){} void loop(){}' > src/main.cpp \
 && pio run -e pockettrainer -e lcd147 >/dev/null 2>&1 || true
COPY src ./src
RUN rm -rf .pio/build && pio run -e pockettrainer -e lcd147
COPY web/tools/package_firmware.py /build/package_firmware.py
RUN python package_firmware.py /build /out

# --- 2. ESP Web Tools (flashing from the browser via Web Serial) ----------------
FROM node:20-alpine AS webtools
ARG ESP_WEB_TOOLS_VERSION=10.4.0
WORKDIR /w
RUN npm pack esp-web-tools@${ESP_WEB_TOOLS_VERSION} >/dev/null && tar xzf esp-web-tools-*.tgz

# --- 3. Static site --------------------------------------------------------------
FROM nginx:1.27-alpine
COPY web/nginx.conf /etc/nginx/conf.d/default.conf
COPY web/index.html /usr/share/nginx/html/index.html
COPY web/img /usr/share/nginx/html/img
COPY --from=webtools /w/package/dist/web /usr/share/nginx/html/vendor/esp-web-tools
COPY --from=firmware /out /usr/share/nginx/html/firmware
EXPOSE 80
