#!/usr/bin/env bash
# Regenerate tests/data/psi-ms-subset.tsv: the PSI-MS OBO entries for every
# MS:/UO: accession that appears in this crate's sources, so tests/cv_terms.rs
# can check each (accession, name) pair offline without vendoring the whole
# ~10 MB ontology.
#
# Usage: scripts/extract-cv-subset.sh PATH/TO/psi-ms.obo[.gz]
#
# The OBO used for the committed file is the copy vendored by mzdata
# (https://github.com/mobiusklein/mzdata, cv/psi-ms.obo.gz). Its
# data-version is recorded in the output header. Rerun after adding a CV
# term to the writer; tests/cv_terms.rs fails if an accession is missing.
set -euo pipefail

obo=${1:?usage: $0 PATH/TO/psi-ms.obo[.gz]}
root=$(cd "$(dirname "$0")/.." && pwd)
out="$root/tests/data/psi-ms-subset.tsv"

read_obo() {
    case "$obo" in
        *.gz) gzip -dc -- "$obo" ;;
        *) cat -- "$obo" ;;
    esac
}

# Reads the whole file (no early exit) so pipefail does not trip on SIGPIPE.
version=$(read_obo | awk -F': ' '/^data-version:/ && v == "" {v = $2} END {print v}')
accessions=$(grep -rhoE '\b(MS|UO):[0-9]{7}\b' "$root/src" "$root/examples" "$root/tests" \
    --include='*.rs' | sort -u)

mkdir -p "$(dirname "$out")"
{
    echo "# PSI-MS CV subset for tests/cv_terms.rs. Generated by"
    echo "# scripts/extract-cv-subset.sh; do not edit by hand."
    echo "# Source: psi-ms.obo data-version ${version} (mzdata cv/psi-ms.obo.gz)."
    echo "# Columns: accession, name, obsolete (true/false)."
    read_obo | awk -v want="$accessions" '
        BEGIN { n = split(want, a, "\n"); for (i = 1; i <= n; i++) keep[a[i]] = 1 }
        function flush() {
            if (id != "" && (id in keep)) print id "\t" name "\t" (obs ? "true" : "false")
            id = ""; name = ""; obs = 0
        }
        /^\[/ { flush(); next }
        /^id: / { id = substr($0, 5); next }
        /^name: / { name = substr($0, 7); next }
        /^is_obsolete: true/ { obs = 1; next }
        END { flush() }
    ' | sort
} > "$out"

missing=$(comm -23 <(echo "$accessions") <(grep -v '^#' "$out" | cut -f1 | sort))
if [ -n "$missing" ]; then
    echo "not found in OBO:" $missing >&2
    exit 1
fi
echo "wrote $out ($(grep -vc '^#' "$out") terms, OBO ${version})"
