# syntax=docker/dockerfile:1.6
# Multi-stage:
#  1) Clona vanna-ai/vanna upstream (commit pinned em 365d061) e builda o webcomponent (~7.5MB)
#  2) Imagem Python 3.11 com vanna editable + requirements + código do app
ARG VANNA_UPSTREAM_COMMIT=365d0617c1a4567ffee1b19b40c27feb4206bfcf

# ============================================================================
# Stage 1 — webcomponent (Node)
# ============================================================================
FROM node:20-bookworm-slim AS webcomponent
ARG VANNA_UPSTREAM_COMMIT
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \
 && rm -rf /var/lib/apt/lists/*
WORKDIR /vanna
RUN git init -q \
 && git remote add origin https://github.com/vanna-ai/vanna.git \
 && git fetch --depth 50 origin "$VANNA_UPSTREAM_COMMIT" \
 && git checkout FETCH_HEAD
WORKDIR /vanna/frontends/webcomponent
RUN npm install --no-audit --no-fund --loglevel=error \
 && npm run build \
 && ls -lh dist/vanna-components.js

# ============================================================================
# Stage 2 — runtime Python
# ============================================================================
FROM python:3.11-slim-bookworm
ARG VANNA_UPSTREAM_COMMIT

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

RUN apt-get update && apt-get install -y --no-install-recommends \
      git ca-certificates curl build-essential \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copia o vanna upstream + bundle já buildado do stage 1
COPY --from=webcomponent /vanna /app/vanna

# Instala vanna editable
RUN pip install -e ./vanna

# Instala deps do app
COPY requirements.txt .
RUN pip install -r requirements.txt

# Código do app
COPY . .

# data dirs
RUN mkdir -p /app/chroma_db /app/data_storage

EXPOSE 8765

# `--workers 1` é OBRIGATÓRIO — múltiplos workers corrompem o SQLite do Chroma
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8765", "--workers", "1"]
