# syntax=docker/dockerfile:1.6
# AION Agent backend (FastAPI + MCP subprocess pool)
# Build context: repository root
#   docker build -f docker/Dockerfile.backend -t aion/backend .

# Versione Python allineata alla .venv del progetto (Python 3.13.x).
# Per cambiare versione: aggiorna entrambi gli stage builder/runtime.
ARG PYTHON_VERSION=3.13-slim@sha256:eb43ff125d8d58d7449dcba7d336c23bcac412f526d861db493b9994d8010280
# uv: digest pinned for OpenSSF Scorecard supply-chain checks.
# https://github.com/astral-sh/uv/pkgs/container/uv
ARG UV_VERSION=latest@sha256:3d868e555f8f1dbc324afa005066cd11e1053fc4743b9808ca8025283e65efa5

# ---------- builder ----------
# uv accelera l'install Python di ~10-50x rispetto a pip. Copiamo il binario
# statico dall'immagine ufficiale (no Rust toolchain richiesta).
FROM ghcr.io/astral-sh/uv:${UV_VERSION} AS uv-bin

FROM python:${PYTHON_VERSION} AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    UV_LINK_MODE=copy \
    UV_COMPILE_BYTECODE=1 \
    UV_PYTHON_DOWNLOADS=never \
    UV_CACHE_DIR=/tmp/uv-cache \
    UV_CONCURRENT_DOWNLOADS=16

# Copia il binario uv dall'immagine ufficiale (~25 MB compresso)
COPY --from=uv-bin /uv /uvx /usr/local/bin/

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

# Creiamo un venv portabile in /opt/venv. Cosi' lo stage runtime puo' copiarlo
# in blocco senza dipendere dal path di python (3.13.x) hardcoded.
RUN uv venv /opt/venv
ENV VIRTUAL_ENV=/opt/venv \
    PATH="/opt/venv/bin:$PATH"

WORKDIR /build
COPY requirements.txt ./

# uv pip install nel venv (VIRTUAL_ENV gia' settato). --no-cache evita che il
# layer porti GB di wheel cache; usiamo cache mount BuildKit per riusare wheel
# tra build successive.
RUN --mount=type=cache,target=/tmp/uv-cache \
    uv pip install --python /opt/venv/bin/python -r requirements.txt

# ---------- runtime ----------
FROM python:${PYTHON_VERSION} AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    VIRTUAL_ENV=/opt/venv \
    PATH="/opt/venv/bin:$PATH" \
    AION_API_HOST=0.0.0.0 \
    AION_API_PORT=8001 \
    AION_DATA_DIR=/app/data

# System dependencies required by Python packages:
# - tesseract-ocr (+ italian) for pytesseract
# - poppler-utils for pdf2image
# - libmagic1 for python-magic style detection
# - tini for clean PID 1 (handles SIGTERM for MCP subprocesses)
# - nodejs 24.x and npm for Node-based MCP servers
# - git for MCP Hub install-github (marketplace git clone)
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl ca-certificates \
    && curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \
    && apt-get install -y --no-install-recommends \
    tesseract-ocr \
    tesseract-ocr-ita \
    poppler-utils \
    libmagic1 \
    tini \
    curl \
    git \
    nodejs \
    podman \
    libreoffice-writer-nogui \
    && rm -rf /var/lib/apt/lists/*

# Node libraries of the office skills, preinstalled globally so the agent does not
# run `npm install` in every session: docx (Word, config/skills/docx) and pptxgenjs
# (PowerPoint, config/skills/pptx). The skills load them with CommonJS require(),
# which honours NODE_PATH; sandbox_install_npm_packages (src/tools/session_npm.py)
# skips packages found there, so no workspace/node_modules (README/LICENSE files the
# channels used to send as "generated files") is created. Excel and python-docx use
# the Python packages of requirements.txt. Deliberately unpinned: latest at build
# time, the same version the agent would get installing them itself (same in
# docker/Dockerfile.sandbox). Docker caches this layer: a plain rebuild keeps the
# version already baked, `docker compose build --no-cache backend` refreshes it.
ENV NODE_PATH=/usr/lib/node_modules:/usr/local/lib/node_modules
RUN npm install -g --no-fund --no-audit --cache /tmp/.npm-cache docx pptxgenjs \
    && rm -rf /tmp/.npm-cache

# Copia il venv (contiene tutti i pacchetti Python + console scripts)
COPY --from=builder /opt/venv /opt/venv

# Copia il binario uv/uvx per consentire all'agente di eseguire server MCP tramite uvx
COPY --from=uv-bin /uv /uvx /usr/local/bin/

# Local speech-to-text model for the stt MCP server (faster-whisper, CTranslate2).
# Downloaded at build time into <AION_STT_LOCAL_MODEL_DIR>/<name>, the layout the
# server looks up first, so the default model never needs network access at runtime.
# Other models chosen later from admin-ui are downloaded into the aion_data volume
# (<AION_DATA_DIR>/models/faster-whisper) and survive container recreation.
# Override the baked size with --build-arg STT_LOCAL_MODEL=base (lighter) or
# large-v3-turbo (heavier, slower on CPU) and set the same AION_STT_LOCAL_MODEL in .env.
ARG STT_LOCAL_MODEL=small
ENV AION_STT_LOCAL_MODEL_DIR=/opt/aion/models/faster-whisper
RUN python -c "from faster_whisper import download_model; download_model('${STT_LOCAL_MODEL}', output_dir='/opt/aion/models/faster-whisper/${STT_LOCAL_MODEL}')"


WORKDIR /app

# mcp-remote proxy for remote-bridge MCP servers (ClickUp, Notion, GitHub Copilot, …)
# Versione fissata (MCP_REMOTE_VERSION in src/mcp_remote_install.py) e lockfile.
COPY docker/package.mcp-remote.json ./package.json
COPY docker/package-lock.mcp-remote.json ./package-lock.json
RUN npm ci --omit=dev

# Application code (runtime dirs config/ and mcp_servers/ come from sync at boot)
COPY src/              ./src/
COPY evals/            ./evals/
COPY mcp_servers_std/  ./mcp_servers_std/
COPY config_std/       ./config_std/
COPY migrations/       ./migrations/
COPY scripts/          ./scripts/
COPY alembic.ini       ./
# Needed at runtime inside the image (GHCR mode has no host bind-mount of the repo):
#   version.json                     -> _read_version() in upgrade_core.py / sync_config.py
#   requirements-sandbox-skills.txt  -> _ensure_skill_packages() during reconcile
COPY version.json      ./
COPY requirements-sandbox-skills.txt ./
COPY docker/backend-entrypoint.sh /usr/local/bin/aion-backend-entrypoint.sh

RUN sed -i 's/\r$//' /usr/local/bin/aion-backend-entrypoint.sh \
    && chmod +x /usr/local/bin/aion-backend-entrypoint.sh \
    && python scripts/sync_config.py --force \
    && python scripts/sync_mcp_servers.py --force

# Writable runtime directories (mounted as volume in compose, created here as fallback)
RUN mkdir -p /app/data /app/data/sessions /app/data/profiles \
    /app/data/skills/generated

EXPOSE 8001

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
    CMD curl -fsS http://127.0.0.1:8001/health || exit 1

ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/aion-backend-entrypoint.sh"]
CMD ["uvicorn", "src.api.main:app", \
    "--host", "0.0.0.0", "--port", "8001", \
    "--workers", "1", \
    "--loop", "asyncio", \
    "--proxy-headers", \
    "--forwarded-allow-ips", "*"]
