#!/usr/bin/env bash
set -euo pipefail

DIR="$1"
BIN="./collect-refs.sh"

# CSV headers
echo 'formula,trim,n_axioms,n_derived,n_rat,duplicates'
echo 'reason,formula' > errors.csv

for file in "$DIR"/*; do
    [ -f "$file" ] || continue
    rel="${file#$DIR/}"

    mapfile -t lines < <("$BIN" "$file")

    case "${#lines[@]}" in
        1)
            idxs=(0)
            ;;
        2)
            idxs=(0 1)
            ;;
        *)
            echo "Error: $file produced ${#lines[@]} lines (expected 1 or 2)" >&2
            exit 1
            ;;
    esac

    for i in "${idxs[@]}"; do
        label=$([ "$i" -eq 0 ] && echo "false" || echo "true")

        read -r f1 f2 f3 rest <<< "${lines[$i]}"

        printf "%s,%s,%s,%s,%s,'%s'\n" \
            "$rel" \
            "$label" \
            "$f1" \
            "$f2" \
            "$f3" \
            "$rest"
    done

    echo $file > /dev/stderr
done

