import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

with open("results.json", "r", encoding="utf-8") as f:
    R = json.load(f)

fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))

# Panel 1: AUROC per arm across seeds
ax = axes[0]
names = [a["name"] for a in R["arms"]]
means = [a["metrics"]["auroc"]["mean"] for a in R["arms"]]
stds = [a["metrics"]["auroc"]["std"] for a in R["arms"]]
colors = ["#888" if a["is_baseline"] else "#2b6cb0" for a in R["arms"]]
ax.bar(range(len(names)), means, yerr=stds, color=colors, capsize=4)
ax.set_xticks(range(len(names)))
ax.set_xticklabels(names, rotation=30, ha="right", fontsize=8)
ax.set_ylabel("AUROC (62-fold LOO, mean over seeds)")
ax.axhline(0.5, color="k", linestyle="--", linewidth=0.8)
ax.set_title("Arm comparison: AUROC")

# Panel 2: Jaccard(top50) distribution across 630 setting-pairs
ax = axes[1]
sw = R["sweep_robustness"]
# reconstruct approx distribution shape using summary stats only (median/p25/p75) as a box-ish view;
# also load raw grid top50 to compute the real histogram
with open("logs/grid_top50.json", "r", encoding="utf-8") as f:
    grid = json.load(f)
keys = list(grid.keys())
sets = {k: set(v) for k, v in grid.items()}
jvals = []
for i in range(len(keys)):
    for j in range(i + 1, len(keys)):
        a, b = sets[keys[i]], sets[keys[j]]
        inter = len(a & b); union = len(a | b)
        jvals.append(inter / union if union else 0.0)
ax.hist(jvals, bins=30, color="#2b6cb0", alpha=0.8)
ax.axvline(0.5, color="red", linestyle="--", label="P1 threshold 0.5")
ax.axvline(np.median(jvals), color="k", linestyle="-", label=f"median={np.median(jvals):.2f}")
ax.set_xlabel("Top-50 Jaccard similarity (630 setting pairs)")
ax.set_ylabel("count")
ax.set_title("Robustness across 36 settings")
ax.legend(fontsize=8)

# Panel 3: degree-null vs pipeline overlap
ax = axes[2]
ov = R["degree_null_vs_pipelines"]["top50_overlap_with_pipelines"]
names2 = list(ov.keys())
vals2 = [ov[n] for n in names2]
ax.bar(names2, vals2, color="#c05621")
ax.axhline(15, color="red", linestyle="--", label="P2 threshold (30% of 50)")
ax.set_ylabel("# genes shared with degree-null Top-50 (out of 50)")
ax.set_xticklabels(names2, rotation=20, ha="right", fontsize=8)
ax.set_title(f"Degree-null AUROC={R['degree_null_vs_pipelines']['degnull_auroc_mean']:.2f}")
ax.legend(fontsize=8)

plt.tight_layout()
plt.savefig("figs/summary.png", dpi=150)
print("wrote figs/summary.png")
