#!/bin/bash
# Produce analysis.txt from the score files. One copy of this rule, called from both places that
# need it (chain.sh, at the end of a full run; finish.sh, when the chain was launched before the
# stage existed).
#
# `analyse.py > analysis.txt` is strictly worse than not running it at all, because the redirect
# truncates the file before the program has produced a byte: a failed rerun replaces a good
# analysis with an empty one, and the staleness guard in build_page.py tests mtime, which an empty
# file passes. So render to a temporary file, check it actually contains an analysis, and only
# then move it into place — atomic, and safe to run twice.
#
# This lived inline in two scripts before it lived here. They had already drifted: one had the
# guarded version and the other had the truncating one-liner, which is the usual outcome of two
# hand-written copies of one rule.
cd "$(dirname "$0")" || exit 1

python3 analyse.py > analysis.new 2>&1
rc=$?
lines=$(wc -l < analysis.new)
# One marker per detector block, plus a floor on length. A traceback is short and contains
# neither; a run that died between the two blocks fails the block count.
blocks=$(grep -c 'adversarial corpus, P(AI)>0.5:' analysis.new)
if [ "$rc" -eq 0 ] && [ "$lines" -ge 40 ] && [ "$blocks" -ge 2 ]; then
    mv analysis.new analysis.txt
    echo "[analysis] analysis.txt written: $lines lines, $blocks detector blocks" >&2
    exit 0
fi
echo "[analysis] REFUSING to write analysis.txt: exit $rc, $lines lines, $blocks detector blocks." >&2
echo "[analysis] any previous analysis.txt is untouched; the failed output is in analysis.new" >&2
tail -5 analysis.new >&2
exit 1
