#!/bin/bash
# Auto-compile LaTeX on file changes
# Writes compile status to compile_status.json for the web UI
cd /data/cameron/para/paper

STATUS_FILE="compile_status.json"

write_status() {
    local ok=$1 msg=$2
    local ts=$(date +"%Y-%m-%d %H:%M:%S")
    echo "{\"ok\": $ok, \"message\": $(echo "$msg" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read().strip()))'), \"timestamp\": \"$ts\"}" > "$STATUS_FILE"
}

write_status true "Watching for changes..."
echo "Watching for .tex changes in $(pwd)..."
echo "PDF served at: https://omidlab.net/paper"

LAST_MOD=0
while true; do
    CURRENT_MOD=$(stat -c %Y main.tex 2>/dev/null || echo 0)
    if [ "$CURRENT_MOD" != "$LAST_MOD" ] && [ "$LAST_MOD" != "0" ]; then
        echo "$(date +%H:%M:%S) — Change detected, compiling..."
        write_status true "Compiling..."
        OUTPUT=$(tectonic main.tex 2>&1)
        EXIT_CODE=$?
        if [ $EXIT_CODE -eq 0 ]; then
            echo "$(date +%H:%M:%S) — Success."
            write_status true "Compiled successfully"
        else
            echo "$(date +%H:%M:%S) — ERROR:"
            echo "$OUTPUT" | tail -10
            write_status false "$OUTPUT"
        fi
    fi
    LAST_MOD=$CURRENT_MOD
    sleep 2
done
