# {{TOOL_NAME}} — utility-web live backend (FastAPI) + built React UI.
# Reads VIP on-behalf-of the logged-in user (the gateway-forwarded `session`
# cookie → vip_auth_headers()); no credential is baked into the image.
# Build context = this tool directory.

# ---- 1) build the React frontend (uses @vianova/ui from the GitLab registry) ----
FROM node:20-slim AS frontend
WORKDIR /fe
COPY app/package.json app/.npmrc ./
# Inject the GitLab read_api token only for `npm install`, via a BuildKit secret.
# Written to .npmrc and overwritten in the SAME layer → token never persists.
RUN --mount=type=secret,id=gitlab_npm_token \
    T="$(cat /run/secrets/gitlab_npm_token)" && \
    { echo "@vianova:registry=https://gitlab.com/api/v4/packages/npm/"; \
      echo "//gitlab.com/api/v4/packages/npm/:_authToken=${T}"; \
      echo "//gitlab.com/api/v4/projects/16624474/packages/npm/:_authToken=${T}"; } > .npmrc && \
    npm install && \
    echo "@vianova:registry=https://gitlab.com/api/v4/packages/npm/" > .npmrc
COPY app/ ./
# The gateway serves the tool under /tools/<slug>/ — build assets + base under
# that prefix (vite.config reads VITE_BASE_PATH; vtFetch resolves /api against it).
ENV VITE_BASE_PATH=/tools/{{TOOL_NAME}}/
RUN npm run build                 # → /fe/dist

# ---- 2) backend image: FROM the platform base, which carries vianova_tool +
#         vianova_streams (serve()/vip_auth_headers() live there). Build the base
#         once with `bin/tool build-base`; keep this tag aligned with
#         coolify/base/Dockerfile. ----
FROM vianova-tools-base:py3.12
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY server.py ./
COPY lib ./lib
COPY --from=frontend /fe/dist ./static
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health',timeout=2).status==200 else 1)"
CMD ["python", "server.py"]
