#!/usr/bin/env bash
# Regenerate the TENDL-2023 MAT table fragment.
#
# Run when TENDL releases a new version (just edit the URL) or when re-validating.
# Output is a Rust source fragment to paste into `crates/endf-mat/src/mat.rs`
# under the existing ENDF_MAT_TABLE definition.
#
# Usage:
#   bash crates/endf-mat/scripts/regenerate_tendl_table.sh > /tmp/tendl_fragment.rs
#
# The script:
#   1. Fetches the IAEA directory listing for TENDL-2023 neutrons sublibrary.
#   2. Parses filenames matching `n_{z:03}-{Sym}-{a}_{mat:04}.zip` into (Z, A, MAT)
#      triples (no metastables — TENDL has none in the neutron sublibrary).
#   3. Sanity-checks each triple (Z ∈ [1,118], A ≥ Z, MAT 4-digit) and fails loud
#      on any anomaly.
#   4. Sorts by (Z, A) for binary-search compatibility.
#   5. Emits a Rust array literal source fragment.

set -euo pipefail

URL="https://www-nds.iaea.org/public/download-endf/TENDL-2023/n/"

listing=$(curl -fsSL --max-time 60 "$URL") || {
    echo "ERROR: failed to fetch $URL (curl returned non-2xx or transport error)" >&2
    exit 1
}
if [ -z "$listing" ]; then
    echo "ERROR: empty listing from $URL" >&2
    exit 1
fi

# Extract triples (Z, A, MAT) from filenames like n_092-U-238_9237.zip
# AWK splits on _ and . to isolate the numeric fields. Z is leading-zero
# padded (3 digits), A is unpadded, MAT is leading-zero padded (4 digits).
triples=$(printf '%s' "$listing" \
    | grep -oE 'n_[0-9]+-[A-Za-z]+-[0-9]+_[0-9]+\.zip' \
    | awk -F'[_.-]' '{ printf "%d %d %d\n", $2, $4, $5 }' \
    | sort -k1,1n -k2,2n \
    | uniq)

count=$(printf '%s\n' "$triples" | wc -l | tr -d ' ')

# Sanity validation
echo "$triples" | awk -v expect_min=2000 -v expect_max=3000 '
    {
        z=$1; a=$2; mat=$3
        if (z < 1 || z > 118)             { printf "ERROR: Z=%d out of range\n", z > "/dev/stderr"; exit 1 }
        if (a < z)                         { printf "ERROR: A=%d < Z=%d\n", a, z > "/dev/stderr"; exit 1 }
        if (mat < 1 || mat > 9999)         { printf "ERROR: MAT=%d out of 4-digit range\n", mat > "/dev/stderr"; exit 1 }
        n++
    }
    END {
        if (n < expect_min || n > expect_max) {
            printf "ERROR: %d entries — outside expected [%d, %d] for TENDL-2023\n", n, expect_min, expect_max > "/dev/stderr"
            exit 1
        }
        printf "validation OK: %d entries\n", n > "/dev/stderr"
    }
'

cat <<EOF
// Auto-generated by crates/endf-mat/scripts/regenerate_tendl_table.sh
// Source: https://www-nds.iaea.org/public/download-endf/TENDL-2023/n/
// $count entries (TENDL-2023 ground-state neutron sublibrary).
// DO NOT EDIT BY HAND — re-run the regenerator if the upstream listing changes.
#[rustfmt::skip]
static TENDL_2023_MAT_TABLE: &[(u32, u32, u32)] = &[
EOF

printf '%s\n' "$triples" | awk '{ printf "    (%d, %d, %d),\n", $1, $2, $3 }'

echo "];"
