"""Case16 visualization only; reads the two final saved CSVs.
Requires existing Python + Matplotlib. No network, study rerun or inference.
Usage:
  python case16-registry-availability-20261012-plot.py availability_summary.csv trial_calculations.csv --out-dir figures
Outputs PNG (300 dpi), SVG, and source-check CSV. Existing files are never overwritten.
Uses saved midpoint groups and saved percentages; trial rows are only cross-checked.
"""
import argparse, collections, csv, hashlib, io
from pathlib import Path
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

PREFIX = "case16-registry-availability-20261012"
GROUPS = ["<1 year", "1–<3 years", "3–<5 years", "≥5 years"]
EXPECTED_HASHES = {
    "availability_summary.csv": "64e40cf520346dd84f3e07310314b3b7a8e5ce44929aa9963967b23e42c8721e",
    "trial_calculations.csv": "ce5be45173e72f859c525876424d87eacd4a9c88d79afce550fbf3232e719da6"
}

def read_table(path, logical_name):
    data = Path(path).read_bytes()
    digest = hashlib.sha256(data).hexdigest()
    assert digest == EXPECTED_HASHES[logical_name], "Not the pinned final source: "+logical_name
    rows = list(csv.DictReader(io.StringIO(data.decode("utf-8-sig"))))
    return rows, digest

def build(summary_path, trials_path, out_dir="."):
    summaries, summary_hash = read_table(summary_path, "availability_summary.csv")
    trials, trial_hash = read_table(trials_path, "trial_calculations.csv")
    assert len({r["nct_id"] for r in trials}) == len(trials)
    assert all(r["included"].lower() in ("true", "false") for r in trials)
    included = [r for r in trials if r["included"].lower() == "true"]
    dates = {r["as_of_date"] for r in included}
    assert len(dates) == 1
    snapshot = next(iter(dates))
    selected = [r for r in summaries if r["scenario"] == "midpoint"]
    assert len({r["stratum"] for r in selected}) == len(selected)
    by_group = {r["stratum"]: r for r in selected}
    assert set(r["stratum_midpoint"] for r in included) <= set(GROUPS)
    checks = []
    for order, group in enumerate(GROUPS, 1):
        s = by_group[group]
        members = [r for r in included if r["stratum_midpoint"] == group]
        counts = collections.Counter(r["has_registry_results"] for r in members)
        assert set(counts) <= {"yes", "no", "unknown"}
        yes, no, unknown = (int(s[k]) for k in ("results_yes", "results_no", "results_unknown"))
        n, denominator = int(s["total_trials"]), int(s["known_denominator"])
        pct = float(s["percent_with_results_known"])
        assert (yes, no, unknown) == (counts["yes"], counts["no"], counts["unknown"])
        assert n == len(members) == yes+no+unknown
        assert denominator == yes+no and unknown == 0 and denominator > 0
        assert abs(pct-100*yes/denominator) <= 0.0051
        assert pct == float(s["percent_with_results_all"])
        checks.append(dict(
            group_order=order, stratum=group, scenario="midpoint", snapshot=snapshot,
            numerator_results_yes=yes, denominator_known=denominator,
            total_trials=n, results_no=no, results_unknown=unknown,
            plotted_percentage=pct, displayed_percentage=f"{pct:.1f}%",
            numerator_denominator_label=f"{yes}/{denominator}",
            trial_row_numerator=counts["yes"], trial_row_denominator=len(members),
            cross_check="PASS", availability_summary_sha256=summary_hash,
            trial_calculations_sha256=trial_hash))
    overall = by_group["Overall"]
    assert sum(r["total_trials"] for r in checks) == len(included) == int(overall["total_trials"])
    assert sum(r["numerator_results_yes"] for r in checks) == int(overall["results_yes"])
    assert sum(r["results_no"] for r in checks) == int(overall["results_no"])
    assert checks[0]["total_trials"] == 1, "Youngest-group disclosure needs review"
    # No confidence intervals exist in the source schema; none are constructed.
    assert not any("confidence" in k.lower() or k.lower().startswith("ci_") for k in selected[0])
    out = Path(out_dir)
    outputs = [out/(PREFIX+suffix) for suffix in (".png", ".svg", "-source-check.csv")]
    assert all(not p.exists() for p in outputs), "Refusing to overwrite an output"
    out.mkdir(parents=True, exist_ok=True)
    plt.rcdefaults()
    plt.rcParams.update({
        "font.family":"DejaVu Sans", "font.size":12, "axes.labelsize":12,
        "xtick.labelsize":11, "ytick.labelsize":12, "text.color":"#20262D",
        "axes.labelcolor":"#20262D", "axes.edgecolor":"#8B9299",
        "figure.facecolor":"white", "axes.facecolor":"white",
        "savefig.facecolor":"white", "svg.fonttype":"none", "svg.hashsalt":PREFIX
    })
    fig, ax = plt.subplots(figsize=(9.4,6.6),dpi=150)
    fig.subplots_adjust(left=0.20,right=0.97,bottom=0.28,top=0.77)
    fig.text(0.045,0.95,"Registry results by time since primary completion",fontsize=14,ha="left",va="top")
    fig.text(0.045,0.895,"Completed glioblastoma trials • phases including phase 2",fontsize=12,ha="left",va="top")
    fig.text(0.045,0.85,"Primary completion 2020–2025 | Snapshot: "+snapshot,fontsize=11,ha="left",va="top")
    ax.axhspan(-0.4,0.4,color="#FFF3D9",zorder=0)
    for i, row in enumerate(checks):
        pct = row["plotted_percentage"]
        ax.hlines(i,0,pct,color="#A8B6C0",linewidth=2,zorder=2)
        ax.scatter(pct,i,s=65,color="#17658A",edgecolor="white",linewidth=0.8,zorder=3)
        ax.text(pct+3,i,
                row["displayed_percentage"]+"  ("+row["numerator_denominator_label"]+")",
                fontsize=12,ha="left",va="center")
    ax.set_yticks(range(len(GROUPS)))
    ax.set_yticklabels([GROUPS[0]+"\nn = 1 (single trial)"]+GROUPS[1:])
    ax.get_yticklabels()[0].set_color("#795415")
    ax.set_ylim(len(GROUPS)-0.5,-0.5)
    ax.set_xlim(-2,100)
    ax.set_xticks(range(0,101,20))
    ax.xaxis.set_major_formatter(PercentFormatter(100,decimals=0))
    ax.set_xlabel("Trials with registry results available",labelpad=12)
    ax.grid(axis="x",color="#E3E7EA",linewidth=0.7,zorder=0)
    ax.set_axisbelow(True)
    ax.tick_params(axis="y",length=0,pad=12)
    ax.tick_params(axis="x",length=3,color="#8B9299")
    for side in ["left","right","top"]: ax.spines[side].set_visible(False)
    fig.text(0.045,0.16,"Labels: percentage (trials with results / trials in group). No confidence intervals.",fontsize=11)
    fig.text(0.045,0.115,"The youngest group contains one trial; its percentage is not a stable group estimate.",fontsize=11)
    fig.text(0.045,0.07,"Availability is not publication, timeliness, compliance or efficacy.",fontsize=11)
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()
    texts = [(t,t.get_window_extent(renderer)) for t in fig.findobj(mpl.text.Text)
             if t.get_visible() and t.get_text().strip()]
    clipped = [t.get_text() for t,b in texts if not (
        b.x0>=fig.bbox.x0 and b.y0>=fig.bbox.y0 and b.x1<=fig.bbox.x1 and b.y1<=fig.bbox.y1)]
    overlaps = [(a.get_text(),b.get_text()) for i,(a,ba) in enumerate(texts)
                for b,bb in texts[i+1:] if ba.overlaps(bb)]
    ticklabels = set(ax.get_xticklabels()+ax.get_yticklabels())
    spine_overlaps = [(t.get_text(),side) for t,bt in texts for side,s in ax.spines.items()
                      if s.get_visible() and t not in ticklabels and bt.overlaps(s.get_window_extent(renderer))]
    assert not clipped and not overlaps and not spine_overlaps, (clipped,overlaps,spine_overlaps)
    fig.savefig(outputs[0],dpi=300)
    fig.savefig(outputs[1],metadata={"Date":None,"Description":"Visualization of pinned final Case16 CSV tables; no new inferential estimates."})
    with outputs[2].open("w",newline="",encoding="utf-8-sig") as f:
        w=csv.DictWriter(f,fieldnames=list(checks[0]))
        w.writeheader()
        w.writerows(checks)
    # Verify no changes to the two original source files.
    assert hashlib.sha256(Path(summary_path).read_bytes()).hexdigest() == summary_hash
    assert hashlib.sha256(Path(trials_path).read_bytes()).hexdigest() == trial_hash
    print("Source reconciliation PASS; original hashes unchanged; text/spine geometry PASS.")
    print("Outputs:",*[str(p) for p in outputs],sep="\n")
    for row in checks: print(row["stratum"],row["displayed_percentage"],row["numerator_denominator_label"])
    plt.close(fig)
    return checks

if __name__ == "__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("summary")
    parser.add_argument("trials")
    parser.add_argument("--out-dir",default=".")
    args=parser.parse_args()
    build(args.summary,args.trials,args.out_dir)
