import json, csv
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family":"DejaVu Sans","font.size":11,"axes.spines.top":False,
                     "axes.spines.right":False,"axes.titleweight":"bold","figure.dpi":140})
ci=json.load(open('bootstrap_ci.json'))
TIER={"gpt-5.4-nano":"budget","gpt-5.4":"mid","gemini-2.5-flash-lite":"budget",
      "gemini-2.5-flash":"budget-mid","claude-haiku-4-5":"budget-mid","claude-sonnet-4-6":"mid"}
TIER_COLOR={"budget":"#d98c5f","budget-mid":"#e0b050","mid":"#4a8fb5"}
# order by chapter acc
order=sorted(ci.keys(), key=lambda m: ci[m][0], reverse=True)
colors=[TIER_COLOR[TIER[m]] for m in order]; y=np.arange(len(order))

# Fig 3 with CI (chapter accuracy)
ca=[ci[m][0] for m in order]; ca_lo=[ci[m][1] for m in order]; ca_hi=[ci[m][2] for m in order]
xerr=[[c-lo for c,lo in zip(ca,ca_lo)],[hi-c for c,hi in zip(ca,ca_hi)]]
fig,ax=plt.subplots(figsize=(8,4.2))
ax.barh(y,ca,color=colors,xerr=xerr,error_kw=dict(ecolor="#333",capsize=3,lw=1))
ax.set_yticks(y); ax.set_yticklabels(order); ax.invert_yaxis()
ax.set_xlabel("Chapter-level accuracy (%)  — mean of 6 languages (95% CI)")
ax.set_title("How often the model places the case in the correct ICD-11 chapter")
for i,(c,hi) in enumerate(zip(ca,ca_hi)): ax.text(hi+1.5,i,f"{c:.0f}%",va="center",fontsize=10)
ax.set_xlim(0,100)
h=[plt.Rectangle((0,0),1,1,color=cc) for cc in TIER_COLOR.values()]
ax.legend(h,TIER_COLOR.keys(),title="capability tier",loc="lower right",frameon=False)
plt.tight_layout(); plt.savefig("fig1_chapter_accuracy.png",bbox_inches="tight"); plt.close()

# Fig 4 with CI (alpha)
al=[ci[m][3] for m in order]; al_lo=[ci[m][4] for m in order]; al_hi=[ci[m][5] for m in order]
xerr=[[a-lo for a,lo in zip(al,al_lo)],[hi-a for a,hi in zip(al,al_hi)]]
fig,ax=plt.subplots(figsize=(8,4.2))
ax.barh(y,al,color=colors,xerr=xerr,error_kw=dict(ecolor="#333",capsize=3,lw=1))
ax.set_yticks(y); ax.set_yticklabels(order); ax.invert_yaxis()
ax.set_xlabel("Krippendorff's alpha (nominal) across 6 languages (95% CI)")
ax.set_title("Cross-lingual consistency: same case, same code across languages?")
for i,(a,hi) in enumerate(zip(al,al_hi)): ax.text(hi+0.008,i,f"{a:.3f}",va="center",fontsize=10)
ax.set_xlim(0,0.5)
plt.tight_layout(); plt.savefig("fig2_alpha.png",bbox_inches="tight"); plt.close()
print("regenerated fig1_chapter_accuracy.png and fig2_alpha.png WITH 95% CI error bars")
