#!/usr/bin/env bash
# One-command reproduction of the seahorse / AD network-pharmacology null-model experiment.
set -euo pipefail
cd "$(dirname "$0")"

mkdir -p data logs figs results_raw
exec > >(tee logs/run.log) 2>&1

echo "=== run.sh started $(date -u +%FT%TZ) ==="

PY=~/joulebeat-evolve/outreach/env/bin/python
export OMP_NUM_THREADS=2
"$PY" -c "import torch; torch.set_num_threads(2)" 2>/dev/null || true

CTD_GZ=data/ctd.tsv.gz
STRING_GZ=data/string.links.gz
PROTEIN_INFO=data/protein.info.txt.gz
KEGG_GMT=data/kegg.gmt
DIS_GMT=data/dis.gmt
GWAS_GMT=data/gwas.gmt

fetch() {
  # fetch URL DEST [CACHE]  -- reuse CACHE if present (speeds up repeat runs in this sandbox),
  # else download fresh with curl. DEST is always what the pipeline reads.
  local url="$1" dest="$2" cache="${3:-}"
  if [ -s "$dest" ]; then
    echo "[fetch] using existing $dest"
  elif [ -n "$cache" ] && [ -s "$cache" ]; then
    echo "[fetch] copying cached $cache -> $dest"
    cp "$cache" "$dest"
  else
    echo "[fetch] downloading $url -> $dest"
    curl -sSL --fail "$url" -o "$dest"
  fi
}

fetch "https://ctdbase.org/reports/CTD_chem_gene_ixns.tsv.gz" "$CTD_GZ" /tmp/ctd.tsv.gz
fetch "https://stringdb-downloads.org/download/protein.links.v12.0/9606.protein.links.v12.0.txt.gz" "$STRING_GZ" /tmp/string.gz
fetch "https://stringdb-downloads.org/download/protein.info.v12.0/9606.protein.info.v12.0.txt.gz" "$PROTEIN_INFO"
fetch "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&libraryName=KEGG_2021_Human" "$KEGG_GMT" /tmp/kegg.gmt
fetch "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&libraryName=DisGeNET" "$DIS_GMT" /tmp/dis.gmt
fetch "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&libraryName=GWAS_Catalog_2025" "$GWAS_GMT" /tmp/gwas.gmt

echo "[prefilter] STRING edges combined_score>=400 (cuts ~13.7M lines down before pandas/dict loading)"
zcat "$STRING_GZ" | awk 'NR==1 || $3>=400' > data/string_ge400.txt
wc -l data/string_ge400.txt

echo "=== PRIMARY RUN: string_cutoff=700, AD geneset=KEGG_2021_Human, n_null=1000, seeds=0,1,2 ==="
"$PY" run_experiment.py \
  --ctd "$CTD_GZ" \
  --string-prefiltered data/string_ge400.txt \
  --protein-info "$PROTEIN_INFO" \
  --kegg-gmt "$KEGG_GMT" \
  --dis-gmt "$DIS_GMT" \
  --string-cutoff 700 \
  --n-null 1000 \
  --seeds 0 1 2 \
  --jaccard-pairs 200 \
  --out-dir .

echo "=== SUPPLEMENTARY SWEEP: string_confidence_cutoff x ad_geneset_source (reduced n_null, seed 0 only) ==="
"$PY" sweep.py \
  --ctd "$CTD_GZ" \
  --string-prefiltered data/string_ge400.txt \
  --protein-info "$PROTEIN_INFO" \
  --kegg-gmt "$KEGG_GMT" \
  --dis-gmt "$DIS_GMT" \
  --gwas-gmt "$GWAS_GMT" \
  --n-null 300 \
  --seed 0 \
  --out-csv results_raw/sweep_results.csv

echo "=== FIGURES ==="
"$PY" make_figures.py

echo "=== run.sh finished $(date -u +%FT%TZ) ==="
