# ─── Stage 1: build the React UI ────────────────────────────────────────
# Pinned to digest to neutralize tag-hijack and supply-chain replay.
# Renovate/dependabot can update this digest periodically.
FROM node:22-alpine@sha256:8ea2348b068a9544dae7317b4f3aafcdc032df1647bb7d768a05a5cad1a7683f AS web-build
WORKDIR /web

# Cache deps separately from sources.
COPY web/package.json web/package-lock.json* ./
RUN npm ci --no-audit --no-fund

COPY web/ .
RUN npm run build

# ─── Stage 2: Python runtime ────────────────────────────────────────────
FROM python:3.13-slim@sha256:a0779d7c12fc20be6ec6b4ddc901a4fd7657b8a6bc9def9d3fde89ed5efe0a3d

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

WORKDIR /app

# gcc — for any pure-Python wheels without prebuilt slim wheels.
# curl + wget — Coolify falls back to wget for its in-container healthcheck.
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc curl wget \
    && rm -rf /var/lib/apt/lists/*

# Install Python deps from pyproject.
COPY pyproject.toml README.md ./
RUN pip install --no-cache-dir .

# App code.
COPY nadlan_mcp/ ./nadlan_mcp/
COPY run_http_server.py ./

# React build artifacts → web/dist (where web_app.py looks for them).
COPY --from=web-build /web/dist ./web/dist

# Non-root user.
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

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

CMD ["python", "run_http_server.py"]
