#!/usr/bin/env bash
# Regenerate Sphinx API reference for every Mnemosyne app, then build HTML.
# Drives both local development and the CI pipeline.
set -euo pipefail

cd "$(dirname "$0")"

APPS=(themis library llm_manager mcp_server)
SOURCE_REF=source/reference/apps
PACKAGE_ROOT=../mnemosyne

make clean

mkdir -p "$SOURCE_REF"

# Per-app subdir so each app gets its own modules.rst (sphinx-apidoc
# overwrites the file otherwise, leaving only the last app in the index).
for app in "${APPS[@]}"; do
    sphinx-apidoc \
        --force \
        --separate \
        --module-first \
        --output-dir "$SOURCE_REF/$app" \
        "$PACKAGE_ROOT/$app" \
        "$PACKAGE_ROOT/$app/migrations" \
        "$PACKAGE_ROOT/$app/tests"
done

# Write a top-level apps.rst that toctree's every app's modules.rst.
{
    echo "Applications"
    echo "============"
    echo
    echo ".. toctree::"
    echo "   :maxdepth: 2"
    echo
    for app in "${APPS[@]}"; do
        echo "   $app/modules"
    done
} > "$SOURCE_REF/index.rst"

make html
