#!/bin/bash

set -e

# Create output directory
mkdir -p pdf

FILENAME="submission"

# Copy bibliography to current directory so bibtex can find it
if [ -f "assets/bibliography/submission.bib" ]; then
    echo "--- Copying submission.bib ---"
    cp assets/bibliography/submission.bib submission.bib
fi

echo "--- Preprocessing Markdown ---"
uv run preprocess.py

echo "--- Generating ${FILENAME}.tex from Markdown using Pandoc ---"
pandoc \
  --standalone \
  --from=markdown+raw_html\
  --output=${FILENAME}.tex \
  --natbib \
  submission_processed.md

echo "--- Compiling ${FILENAME}.tex to PDF ---"
echo "  > Running pdflatex (first pass)..."
pdflatex -interaction=nonstopmode -output-directory=pdf ${FILENAME}.tex

echo "  > Running bibtex..."
bibtex pdf/${FILENAME}

echo "  > Running pdflatex (second pass)..."
pdflatex -interaction=nonstopmode -output-directory=pdf ${FILENAME}.tex

echo "  > Running pdflatex (final pass)..."
pdflatex -interaction=nonstopmode -output-directory=pdf ${FILENAME}.tex

echo "--- Moving source artifacts to pdf/ ---"
mv ${FILENAME}.tex pdf/
mv submission_processed.md pdf/
if [ -f "submission.bib" ]; then
    mv submission.bib pdf/
fi

echo "--- Done! PDF generated: pdf/${FILENAME}.pdf ---"
