"""GO Biological Process over-representation analysis, re-run 14 Nov 2026.
Study:  B-cell pseudobulk DEGs (BH FDR < 0.05) from B_cell_SLE_vs_Healthy_DE_results.csv
Universe: all genes tested in the same DE analysis
Annotations: GOA human GAF (geneontology.org), GO ontology releases/2026-07-26
Method: Fisher exact test, BH FDR, GOATOOLS 1.6.9, propagate_counts=True
"""
import csv, gzip, json
from collections import defaultdict
from goatools.obo_parser import GODag
from goatools.go_enrichment import GOEnrichmentStudy

BASE = "/home/hatch/workspace/single-cell-sle-report"
REPO = BASE + "/SLE-RNA-Therapeutic-Discovery"

# 1. Load DE results (limma topTable; first column = gene symbol)
tested, degs = [], []
with open(REPO + "/results/B_cell_SLE_vs_Healthy_DE_results.csv") as fh:
    for row in csv.DictReader(fh):
        sym = row[""]
        tested.append(sym)
        if float(row["adj.P.Val"]) < 0.05:
            degs.append(sym)
print("tested:", len(tested), "DEGs FDR<0.05:", len(degs))

# 2. Parse GAF: symbol -> GO terms (exclude NOT qualifiers)
sym2go = defaultdict(set)
with gzip.open(BASE + "/go_data/goa_human.gaf.gz", "rt") as fh:
    for line in fh:
        if line.startswith("!"):
            continue
        f = line.rstrip("\n").split("\t")
        if len(f) < 15:
            continue
        symbol, qualifier, goid, taxon = f[2], f[3], f[4], f[12]
        if "NOT" in qualifier.split("|"):
            continue
        if "9606" not in taxon:
            continue
        sym2go[symbol].add(goid)
print("symbols with GO annotations in GAF:", len(sym2go))

# 3. Study / population restricted to annotated genes
pop = [g for g in tested if g in sym2go]
study = [g for g in degs if g in sym2go]
print("universe (annotated tested genes):", len(pop))
print("study (annotated DEGs):", len(study))

# 4. Enrichment, BP only
obodag = GODag(BASE + "/go_data/go-basic.obo")
goea = GOEnrichmentStudy(pop, sym2go, obodag, propagate_counts=True,
                         alpha=0.05, methods=["fdr_bh"])
results = goea.run_study(study)
bp = [r for r in results if r.NS == "BP" and r.p_fdr_bh < 0.05]
bp.sort(key=lambda r: r.p_fdr_bh)
print("significant BP terms (FDR<0.05):", len(bp))

# 5. Write results
with open(BASE + "/GO_BP_rerun_2026-11-14.csv", "w", newline="") as fh:
    w = csv.writer(fh)
    w.writerow(["ID", "Description", "GeneRatio", "BgRatio", "pvalue", "p.adjust",
               "study_count", "study_total", "pop_count", "pop_total", "genes"])
    for r in bp:
        w.writerow([r.GO, r.name, f"{r.study_count}/{r.study_n}",
                    f"{r.pop_count}/{r.pop_n}", f"{r.p_uncorrected:.6g}",
                    f"{r.p_fdr_bh:.6g}", r.study_count, r.study_n,
                    r.pop_count, r.pop_n, ";".join(sorted(r.study_items))])

# 6. Compare with the original 94-term file
orig = list(csv.DictReader(open(REPO + "/results/B_cell_GO_BP_enrichment.csv")))
orig_ids = {r["ID"] for r in orig}
new_ids = {r.GO for r in bp}
print("original terms:", len(orig_ids), "| rerun terms:", len(new_ids),
      "| overlap:", len(orig_ids & new_ids))
print("original-only:", len(orig_ids - new_ids), "| rerun-only:", len(new_ids - orig_ids))
json.dump({"tested": len(tested), "degs": len(degs), "pop": len(pop),
           "study": len(study), "n_bp_sig": len(bp),
           "overlap": len(orig_ids & new_ids),
           "orig_only": sorted(orig_ids - new_ids),
           "rerun_only": sorted(new_ids - orig_ids)},
          open(BASE + "/GO_comparison_summary.json", "w"), indent=1)
print("TOP 10 rerun terms:")
for r in bp[:10]:
    print(" ", r.GO, r.name, "FDR=%.3g" % r.p_fdr_bh, f"({r.study_count}/{r.study_n})")
