# ─── Stage 1: build the React UI ────────────────────────────────────────
FROM node:22-alpine 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

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  — Coolify runs its healthcheck via curl inside the container.
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc curl \
    && 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:${PORT:-8000}/health')" || exit 1

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