#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Build the Insight demo and documentation.
# Existing files under $DOCS_DIR that are not generated by the browser build
# are copied aside before the directory is wiped. After unzipping the new
# bundle, those files are restored so manual assets like images or PDFs survive
# across rebuilds.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"

BROWSER_DIR="alpha_factory_v1/demos/alpha_agi_insight_v1/insight_browser_v1"
DOCS_DIR="docs/alpha_agi_insight_v1"

usage() {
    cat <<USAGE
Usage: $0

Build the Insight browser bundle, refresh $DOCS_DIR
and generate the mkdocs site.
USAGE
}

if [[ "${1:-}" =~ ^(-h|--help)$ ]]; then
    usage
    exit 0
fi

# Ensure the correct Node.js version before running npm
if ! node "$BROWSER_DIR/build/version_check.js"; then
    echo "ERROR: Node.js 22+ is required to build the Insight docs." >&2
    exit 1
fi

# Fetch WASM assets then install Node dependencies and build the browser bundle
npm --prefix "$BROWSER_DIR" run fetch-assets
npm --prefix "$BROWSER_DIR" ci
(cd "$BROWSER_DIR" && npx update-browserslist-db --update-db --yes)
npm --prefix "$BROWSER_DIR" run build:dist

# Refresh docs directory with the new bundle while preserving all
# non-generated files (e.g. images or additional Markdown docs)
OLD_DOCS_TEMP=""
if [[ -d "$DOCS_DIR" ]]; then
    OLD_DOCS_TEMP="$(mktemp -d)"
    cp -a "$DOCS_DIR/." "$OLD_DOCS_TEMP/"
fi
rm -rf "$DOCS_DIR"
mkdir -p "$DOCS_DIR"
unzip -q -o "$BROWSER_DIR/insight_browser.zip" -d "$DOCS_DIR"
# Copy the quickstart guide from the build output so the docs include it
PDF_SRC="$BROWSER_DIR/dist/assets/insight_browser_quickstart.pdf"
if [[ -f "$PDF_SRC" ]]; then
    cp -a "$PDF_SRC" "$DOCS_DIR/"
fi
# Ensure the service worker and PWA files exist in the docs directory
unzip -q -j -o "$BROWSER_DIR/insight_browser.zip" service-worker.js -d "$DOCS_DIR" || true
unzip -q -j -o "$BROWSER_DIR/insight_browser.zip" assets/manifest.json -d "$DOCS_DIR" || true
mkdir -p "$DOCS_DIR/assets/lib"
unzip -q -j -o "$BROWSER_DIR/insight_browser.zip" assets/lib/workbox-sw.js -d "$DOCS_DIR/assets/lib" || true
if [[ -n "$OLD_DOCS_TEMP" ]]; then
    while IFS= read -r -d '' file; do
        rel="${file#"$OLD_DOCS_TEMP"/}"
        target="$DOCS_DIR/$rel"
        if [[ ! -e "$target" ]]; then
            mkdir -p "$(dirname "$target")"
            cp -a "$file" "$target"
        fi
    done < <(find "$OLD_DOCS_TEMP" -mindepth 1 -print0)
    # Ensure the Plotly license file accompanies plotly.min.js
    LICENSE_FILE="plotly.min.js.LICENSE.txt"
    if [[ ! -f "$DOCS_DIR/$LICENSE_FILE" && -f "$OLD_DOCS_TEMP/$LICENSE_FILE" ]]; then
        cp -a "$OLD_DOCS_TEMP/$LICENSE_FILE" "$DOCS_DIR/"
    fi
    rm -rf "$OLD_DOCS_TEMP"
fi

LICENSE_FILE="plotly.min.js.LICENSE.txt"
if [[ ! -f "$DOCS_DIR/$LICENSE_FILE" && -f "$REPO_ROOT/docs/alpha_agi_insight_v1/$LICENSE_FILE" ]]; then
    cp -a "$REPO_ROOT/docs/alpha_agi_insight_v1/$LICENSE_FILE" "$DOCS_DIR/"
fi

# Ensure the favicon survives extraction
ICON_FILE="favicon.svg"
if [[ ! -f "$DOCS_DIR/$ICON_FILE" && -f "$BROWSER_DIR/$ICON_FILE" ]]; then
    cp -a "$BROWSER_DIR/$ICON_FILE" "$DOCS_DIR/"
fi

# Export the latest meta-agent tree when lineage data is available
TREE_INPUT="lineage/run.jsonl"
TREE_OUTPUT="$DOCS_DIR/tree.json"
if [[ -f "$TREE_INPUT" ]]; then
    python alpha_factory_v1/demos/alpha_agi_insight_v1/tools/export_tree.py \
        "$TREE_INPUT" -o "$TREE_OUTPUT"
else
    echo "WARNING: $TREE_INPUT not found; skipping tree export" >&2
fi

# Validate the bundled workbox file before generating docs
if ! python scripts/verify_workbox_hash.py "$DOCS_DIR"; then
    echo "ERROR: Workbox hash verification failed" >&2
    exit 1
fi

# Copy static assets from other demos so MkDocs can serve them
copy_assets() {
    mkdir -p docs/aiga_meta_evolution/assets
    cp alpha_factory_v1/demos/aiga_meta_evolution/bridge_overview.svg \
        docs/aiga_meta_evolution/assets/bridge_overview.svg
    for demo in meta_agentic_agi meta_agentic_agi_v2 meta_agentic_agi_v3; do
        src="alpha_factory_v1/demos/$demo/ui/assets"
        dest="docs/$demo/assets"
        mkdir -p "$dest"
        cp -a "$src"/* "$dest/"
    done

    # Copy Pyodide runtime files for the gallery
    wasm_src="$BROWSER_DIR/wasm"
    pyodide_dest="docs/assets/pyodide"
    mkdir -p "$pyodide_dest"
    cp -a "$wasm_src"/pyodide.* "$pyodide_dest/"
}
copy_assets

# Regenerate Markdown pages for each demo from their README files
python scripts/generate_demo_docs.py
python scripts/generate_gallery_html.py

# Build the MkDocs site. Strict mode is always enabled so any warnings
# surface as errors both locally and in CI.
mkdocs build --strict

# Verify the Workbox hash again in the generated site directory
if ! python scripts/verify_workbox_hash.py site/alpha_agi_insight_v1; then
    echo "ERROR: Workbox hash verification failed for generated site" >&2
    exit 1
fi



