#!/bin/bash
# The last stage of this study is not in chain.run.sh, because chain.run.sh was already executing
# by the time I knew it was needed and a running bash script must not be edited (it is read by
# byte offset, hours later, mid-token). So the analysis stage waits out here instead.
#
# build_page.py refuses to render if analysis.txt is missing OR older than any scores_*.jsonl or
# padding_*.jsonl, which means forgetting this step cannot silently publish stale numbers — it
# just blocks the build at the end of an eleven-hour chain. Running it automatically is cheaper
# than remembering it.
#
# I wrote here that this was a *redundant* second run, because chain.sh ends with analyse.py. It
# is not: chain.sh grew that stage at 08:24 and the executing copy, chain.run.sh, was taken at
# 08:05. I described the running system from the source file instead of from the process, which is
# the same mistake as describing an artifact from memory of a log. This run is the only one, and
# if it refuses there is no analysis.txt at all — which is loud (build_page.py refuses on a
# missing analysis.txt) rather than silent, so the behaviour is right and only the comment was
# wrong.
#
# The validate-then-move logic now lives in run_analysis.sh, called from here and from chain.sh.
#
# Waits on a FILE, never on a pgrep: a waiter whose pattern matches its own command line waits
# forever. "[chain] all done" is written only after the last padding check returns.
#
#   cp finish.sh finish.run.sh && setsid nohup ./finish.run.sh <chain-pid> > finish.log 2>&1 < /dev/null &
cd /home/agent/work/aidetect-fpr

CHAIN_PID="${1:-}"
while ! grep -q '^\[chain\] all done' chain.log 2>/dev/null; do
    if [ -n "$CHAIN_PID" ] && [ ! -d "/proc/$CHAIN_PID" ]; then
        echo "[finish] chain PID $CHAIN_PID is gone and chain.log never said all done — stopping." >&2
        echo "[finish] $(wc -l < scores_hello.jsonl 2>/dev/null) hello, $(wc -l < scores_openai.jsonl 2>/dev/null) openai corpus rows at the time." >&2
        exit 1
    fi
    sleep 60
done

echo "[finish] chain complete, running the analysis" >&2
./run_analysis.sh
# Deliberately does NOT run build_page.py. Seven strings in copy.json are written after the
# numbers are known — the title, the lede, and five section strings whose wording depends on how
# the result comes out. A build before those are authored would render placeholders into a page.
echo "[finish] next step is manual: author the pending copy.json strings, then build_page.py" >&2
