#!/usr/bin/env bash
# Build the Financial Innovation submission PDF.
# Chain: pdflatex → bibtex → pdflatex → pdflatex (sn-jnl.cls defaults to bibtex, NOT biber)
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PAPER="$ROOT/paper"

cd "$PAPER"

if [ "${1:-}" = "--dry-run" ]; then
    echo "Would run:"
    echo "  pdflatex -interaction=nonstopmode main.tex"
    echo "  bibtex main"
    echo "  pdflatex -interaction=nonstopmode main.tex"
    echo "  pdflatex -interaction=nonstopmode main.tex"
    exit 0
fi

if [ ! -f main.tex ]; then
    echo "ERROR: $PAPER/main.tex not found (Phase 2 must run first)"
    exit 2
fi

# C-303 pre-build: ampersand-safety gate on refs.bib
# Fails if any @-entry has an unescaped "& " inside journal/booktitle value.
if grep -nE '^[[:space:]]*(journal|booktitle)[[:space:]]*=[[:space:]]*\{[^}]*[^\\]&[[:space:]]' "$PAPER/bib/refs.bib" > /dev/null 2>&1; then
    echo "BUILD FAILED: unescaped '&' in refs.bib journal/booktitle field"
    grep -nE '^[[:space:]]*(journal|booktitle)[[:space:]]*=[[:space:]]*\{[^}]*[^\\]&[[:space:]]' "$PAPER/bib/refs.bib"
    exit 3
fi

echo "[1/4] pdflatex"
pdflatex -interaction=nonstopmode main.tex > build.log 2>&1 || true
echo "[2/4] bibtex"
bibtex main >> build.log 2>&1 || true
echo "[3/4] pdflatex"
pdflatex -interaction=nonstopmode main.tex >> build.log 2>&1 || true
echo "[4/4] pdflatex"
pdflatex -interaction=nonstopmode main.tex >> build.log 2>&1

if grep -q "! LaTeX Error" build.log; then
    echo "BUILD FAILED: LaTeX errors found in build.log"
    grep "! LaTeX Error" build.log | head -10
    exit 1
fi
if grep -q "Citation .* undefined" build.log; then
    echo "BUILD WARNING: undefined citations"
    grep "Citation .* undefined" build.log | head -5
fi
# D-402 post-build hard gates
if [ -f main.pdf ]; then
    # Gate 1: main.bbl has >= 40 bibitem
    bib_count=$(grep -c '\\bibitem' main.bbl 2>/dev/null || echo 0)
    if [ "$bib_count" -lt 40 ]; then
        echo "BUILD FAILED: main.bbl has only $bib_count bibitem entries (expected >= 40)"
        exit 4
    fi
    # Gate 2: zero undefined citations in final pass
    # extract final-pass content (after 3rd 'This is pdfTeX' banner)
    if awk 'BEGIN{p=0}/^This is pdfTeX/{p++}p==4' build.log | grep -q "Citation .* undefined"; then
        echo "BUILD FAILED: undefined citations in final pass"
        awk 'BEGIN{p=0}/^This is pdfTeX/{p++}p==4' build.log | grep "Citation .* undefined" | head -5
        exit 5
    fi
    # Gate 3: no ! LaTeX Error in any pass (redundant with earlier check but keeps gate explicit)
    if grep -q "^! " build.log; then
        echo "BUILD FAILED: LaTeX errors present"
        grep "^! " build.log | head -5
        exit 6
    fi
    echo "BUILD OK: main.pdf (bibitems=$bib_count, post-build gates PASS)"

    # Advisory hostile-audit gate (non-blocking).
    # The trailing `|| true` swallows audit_refs.py's exit 1 on hostile flags.
    # To enforce hard-block once the current 5 hostile_flag entries are triaged,
    # remove the `|| true` and let `set -e` propagate the exit code.
    if [ -f "$ROOT/scripts/audit_refs.py" ]; then
        echo "[advisory] hostile audit:"
        ( cd "$ROOT" && python scripts/audit_refs.py --hostile 2>&1 | tail -3 ) || true
    fi

    exit 0
fi
echo "BUILD FAILED: main.pdf not produced"
exit 1
