#!/bin/bash
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
SRC="$DIR/draft-nennemann-act-01.md"

# Extract docname from YAML front matter
DRAFT=$(grep '^docname:' "$SRC" | head -1 | awk '{print $2}')
if [ -z "$DRAFT" ]; then
  echo "Error: could not extract docname from $SRC"
  exit 1
fi

# Tool paths
KRAMDOWN="$(which kramdown-rfc2629 2>/dev/null)"
XML2RFC="$(which xml2rfc 2>/dev/null)"

if [ -z "$KRAMDOWN" ]; then
  echo "Error: kramdown-rfc2629 not found. Install with: gem install kramdown-rfc2629"
  exit 1
fi
if [ -z "$XML2RFC" ]; then
  echo "Error: xml2rfc not found. Install with: pip install xml2rfc"
  exit 1
fi

export PYTHONWARNINGS="ignore::UserWarning"

echo "Building: $DRAFT"
echo "Using kramdown-rfc2629: $KRAMDOWN"
echo "Using xml2rfc:          $XML2RFC"
echo ""

# Step 1: Markdown -> XML
echo "Converting markdown to XML..."
"$KRAMDOWN" "$SRC" > "$DIR/$DRAFT.xml"

# Step 2: XML -> TXT
echo "Generating text output..."
"$XML2RFC" "$DIR/$DRAFT.xml" --text --quiet 2>/dev/null

# Step 3: XML -> HTML
echo "Generating HTML output..."
"$XML2RFC" "$DIR/$DRAFT.xml" --html --quiet 2>/dev/null

# Step 4: XML -> PDF (requires weasyprint + pangocffi + pycairo injected into xml2rfc venv
# and pydyf<0.10 pinned; see /home/c/projects/research.ietf/workspace/drafts/README-pdf.md)
echo "Generating PDF output..."
if "$XML2RFC" "$DIR/$DRAFT.xml" --pdf --quiet 2>/dev/null; then
  PDF_OK=1
else
  echo "  xml2rfc --pdf failed; falling back to weasyprint on HTML"
  if command -v weasyprint >/dev/null 2>&1; then
    weasyprint "$DIR/$DRAFT.html" "$DIR/$DRAFT.pdf" >/dev/null 2>&1 && PDF_OK=1 || PDF_OK=0
  else
    PDF_OK=0
  fi
fi

echo ""
echo "Build complete:"
echo "  $DRAFT.xml   (submit this to datatracker)"
echo "  $DRAFT.txt"
echo "  $DRAFT.html"
if [ "${PDF_OK:-0}" = "1" ]; then
  echo "  $DRAFT.pdf"
else
  echo "  (PDF generation skipped — missing deps)"
fi
