# ---- Stage: build frontend ----
FROM node:22-alpine AS frontend-build
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm install
COPY frontend/ ./
RUN npm run build
# Output: /app/static/

# ---- Target: poller (hardware producer) ----
# Privileged at runtime; the only image with SAS/SMART tooling. Slim Python
# deps (just Redis) — no web stack.
FROM python:3.13-slim AS poller

RUN apt-get update && apt-get install -y --no-install-recommends \
    smartmontools \
    sg3-utils \
    lsscsi \
    util-linux \
    ledmon \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

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

COPY poller.py .
COPY services/ services/

CMD ["python", "-u", "poller.py"]

# ---- Target: host-poller (chassis IPMI/iDRAC + CPU + on-metal drives) ----
# Privileged at runtime (needs /dev/ipmi0 + raw disks). Carries ipmitool +
# smartmontools; no SAS-shelf tooling.
FROM python:3.13-slim AS host-poller

RUN apt-get update && apt-get install -y --no-install-recommends \
    ipmitool \
    smartmontools \
    util-linux \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

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

COPY host_poller.py .
COPY services/ services/

CMD ["python", "-u", "host_poller.py"]

# ---- Target: web (read-only consumer) ----
# Unprivileged at runtime; no hardware tools. Serves REST/UI + MQTT, reads Redis.
FROM python:3.13-slim AS web

WORKDIR /app

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

COPY main.py .
COPY routers/ routers/
COPY services/ services/
COPY models/ models/
COPY --from=frontend-build /app/static/ static/

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/health')" || exit 1

# Single worker: the MQTT publisher is a per-process singleton (multiple
# workers would connect with the same client_id and flap the broker). The
# API is a low-traffic internal monitor, so one worker is plenty.
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
