# ----------------------------------------------------------------------------
# Art IoT — one image: OCPP 1.6J CSMS + REST API + Tuya relay control, serving
# the built React panel. Two stages:
#   1. node builds frontend/ -> dist/
#   2. python:slim runs `python -m backend.main` on :9000, with dist/ where
#      backend/main.py expects it (/app/frontend/dist).
#
# All mutable state (backend.db, events.jsonl) lives on the /data volume via
# the BACKEND_DB / BACKEND_EVENTS env overrides — the container is disposable.
#
# Build:  docker build -t artiot:dev .
# Run:    docker run -p 9000:9000 -v artiot-data:/data artiot:dev
# ----------------------------------------------------------------------------

FROM node:24-alpine AS panel
WORKDIR /build
# deps first — separate layer so source edits don't bust the npm cache
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build


FROM python:3.13-slim

# curl for the compose healthcheck; tini reaps zombies and forwards SIGTERM so
# `docker stop` shuts uvicorn down cleanly (capped at 3s by main.py, because
# the charger holds its WebSocket open forever).
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        ca-certificates \
        curl \
        tini \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Python deps first — separate layer, pinned exactly to requirements.txt.
COPY backend/requirements.txt /app/backend/requirements.txt
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r /app/backend/requirements.txt

COPY backend/ /app/backend/
COPY --from=panel /build/dist/ /app/frontend/dist/

# Persistent state. Owned by UID 1000 so the non-root process can write it.
RUN mkdir -p /data && chown -R 1000:1000 /data
ENV BACKEND_DB=/data/backend.db \
    BACKEND_EVENTS=/data/events.jsonl \
    PYTHONUNBUFFERED=1
VOLUME ["/data"]

# 9000 is load-bearing: hardcoded in the charger's touchscreen URL.
EXPOSE 9000

USER 1000:1000
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["python", "-m", "backend.main"]
