"""Headline charts for the Mining Cost Standard publication.
Usage: make_charts.py <period e.g. Q3_2026> <xlsx> [out_dir]
Reads engine_result.json (stacks per ticker|period) and renders cost_stack_<per>_{light,dark}.svg + .png (stacked bars: energy / other direct /
allocated cash SG&A (= L1) / D&A attributable; tick = realized price) and l1_ttm_<cut>.png (TTM L1 by company).
Palette = dataviz reference instance (validated: 4 adjacent slots pass light mode; contrast relief via direct labels)."""
import json, sys, os
SP=os.environ.get("COST_DIR") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
per=sys.argv[1]; xl=sys.argv[2]; OUTD=sys.argv[3] if len(sys.argv)>3 else os.path.join(SP,"charts"); os.makedirs(OUTD,exist_ok=True)
E=json.load(open(f"{SP}/engine_result.json")); S=E["stacks"]
LQ,LY=per.split("_"); CUT=f"{LY}{LQ}"
LIGHT={"surface":"#fcfcfb","text":"#0b0b0b","text2":"#52514e","grid":"#e6e5e1","s1":"#2a78d6","s2":"#eb6834","s3":"#1baf7a","s4":"#eda100"}
DARK ={"surface":"#1a1a19","text":"#f0efec","text2":"#c3c2b7","grid":"#33332f","s1":"#3987e5","s2":"#d95926","s3":"#199e70","s4":"#c98500"}
rows=[]
for key,st in S.items():
    t,p=key.split("|")
    if p!=per or st.get("Y") is None: continue
    J=st.get("_J"); Fq=st.get("_F"); en=(J/Fq) if (isinstance(J,(int,float)) and isinstance(Fq,(int,float)) and Fq) else None
    en_draw=min(en,st["Q"]) if en is not None else None   # credits (WULF DR) can pull L0 NET below gross energy: draw energy net so segments sum to L1
    rows.append(dict(t=t,energy=en_draw if en_draw is not None else 0.0, other=(st["Q"]-en_draw) if en_draw is not None else st["Q"], sga=st["X"], da=st.get("AH") or 0.0, price=st["AM"], l1=st["Y"], l3=st.get("AI"), hl=st["AW"], e_missing=en is None))
rows.sort(key=lambda r:r["l1"])
head=[r for r in rows if r["hl"]=="HEADLINE"]; app=[r for r in rows if r["hl"]!="HEADLINE"]
rows=head+app
W=980; LM=150; RM=40; TOP=70; BH=26; GAP=12; H=TOP+len(rows)*(BH+GAP)+90
xmax=max(max((r["l1"]+r["da"]) for r in rows), max(r["price"] for r in rows))*1.08
def X(v): return LM+(W-LM-RM)*v/xmax
def svg(c,name):
    out=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" font-family="IBM Plex Sans, Arial, sans-serif" style="background:{c["surface"]}">',f'<rect width="{W}" height="{H}" fill="{c["surface"]}"/>']
    out.append(f'<text x="{LM}" y="26" font-size="17" font-weight="600" fill="{c["text"]}">Cost to mine one bitcoin — public miners, {LQ} {LY}</text>')
    out.append(f'<text x="{LM}" y="46" font-size="12" fill="{c["text2"]}">Stacked: energy · other direct · allocated cash SG&amp;A (= L1 cash operating cost) · D&amp;A attributable (→ L3). Tick = realized price (BTC revenue ÷ BTC mined). Source: SEC filings, HASHFLOPS Mining Cost Standard v1.0.</text>')
    g=0
    while g<=xmax:
        x=X(g); out.append(f'<line x1="{x:.1f}" y1="{TOP-8}" x2="{x:.1f}" y2="{H-60}" stroke="{c["grid"]}" stroke-width="1"/>'); out.append(f'<text x="{x:.1f}" y="{H-44}" font-size="11" text-anchor="middle" fill="{c["text2"]}">${g//1000}k</text>'); g+=20000
    y=TOP
    for i,r in enumerate(rows):
        if i==len(head) and app: out.append(f'<text x="{LM}" y="{y+6}" font-size="11" fill="{c["text2"]}" font-style="italic">appendix — below materiality threshold / hosted (Tier 2)</text>'); y+=18
        label=r["t"]; out.append(f'<text x="{LM-10}" y="{y+BH/2+4}" font-size="12" text-anchor="end" fill="{c["text"]}" font-weight="600">{label}</text>')
        segs=[("Energy",r["energy"],c["s1"]),("Other direct",r["other"],c["s2"]),("Allocated cash SG&A",r["sga"],c["s3"]),("D&A attributable",r["da"],c["s4"])]
        if r["e_missing"]: segs[0]=("Energy (not split)",0,c["s1"]); segs[1]=("Direct (energy not split)",r["other"],c["s2"])
        x0=0
        for j,(nm,val,col) in enumerate(segs):
            if not val or val<=0: continue
            x1=X(x0); x2=X(x0+val); wseg=max(0,x2-x1-2)
            rx=4 if j==3 or (j<3 and all((segs[k][1] or 0)<=0 for k in range(j+1,4))) else 0
            out.append(f'<rect x="{x1:.1f}" y="{y}" width="{wseg:.1f}" height="{BH}" fill="{col}" rx="{rx}"><title>{label} — {nm}: ${val:,.0f}/BTC</title></rect>')
            if wseg>44: out.append(f'<text x="{x1+wseg/2:.1f}" y="{y+BH/2+4}" font-size="10" text-anchor="middle" fill="{"#ffffff" if j in (0,1) else c["text"]}">${val/1000:.1f}k</text>')
            x0+=val
        out.append(f'<text x="{X(r["l1"])+4:.1f}" y="{y-3}" font-size="10" fill="{c["text2"]}">L1 ${r["l1"]/1000:.1f}k</text>')
        xp=X(r["price"]); out.append(f'<line x1="{xp:.1f}" y1="{y-4}" x2="{xp:.1f}" y2="{y+BH+4}" stroke="{c["text"]}" stroke-width="2"><title>{label} — realized price ${r["price"]:,.0f}/BTC</title></line>')
        y+=BH+GAP
    ly=H-20; lx=LM
    for nm,col in [("Energy (L0-E)",c["s1"]),("Other direct cost",c["s2"]),("Allocated cash SG&A",c["s3"]),("D&A attributable",c["s4"])]:
        out.append(f'<rect x="{lx}" y="{ly-10}" width="12" height="12" fill="{col}" rx="2"/>'); out.append(f'<text x="{lx+16}" y="{ly}" font-size="11" fill="{c["text2"]}">{nm}</text>'); lx+=len(nm)*6.6+40
    out.append(f'<line x1="{lx}" y1="{ly-10}" x2="{lx}" y2="{ly+2}" stroke="{c["text"]}" stroke-width="2"/>'); out.append(f'<text x="{lx+8}" y="{ly}" font-size="11" fill="{c["text2"]}">Realized price</text>')
    out.append('</svg>'); open(f"{OUTD}/{name}","w").write("\n".join(out))
svg(LIGHT,f"cost_stack_{per}_light.svg"); svg(DARK,f"cost_stack_{per}_dark.svg")
try:
    import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
    from matplotlib.patches import Patch; from matplotlib.lines import Line2D
    fig,ax=plt.subplots(figsize=(11,0.45*len(rows)+2.2),dpi=160); fig.patch.set_facecolor(LIGHT["surface"]); ax.set_facecolor(LIGHT["surface"])
    ys=list(range(len(rows)))[::-1]
    for r,yy in zip(rows,ys):
        left=0
        for val,col in [(r["energy"],LIGHT["s1"]),(r["other"],LIGHT["s2"]),(r["sga"],LIGHT["s3"]),(r["da"],LIGHT["s4"])]:
            if val and val>0: ax.barh(yy,val,left=left,color=col,height=0.62,edgecolor=LIGHT["surface"],linewidth=1.5); left+=val
        ax.plot([r["price"],r["price"]],[yy-0.42,yy+0.42],color=LIGHT["text"],linewidth=2)
        ax.text(r["l1"]+1500,yy+0.36,f"L1 ${r['l1']/1000:.1f}k",fontsize=7.5,color=LIGHT["text2"])
    ax.set_yticks(ys); ax.set_yticklabels([r["t"]+("" if r["hl"]=="HEADLINE" else " *") for r in rows],fontsize=9)
    ax.set_xlim(0,xmax); ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v,p:f"${v/1000:.0f}k"))
    for sp in ["top","right","left"]: ax.spines[sp].set_visible(False)
    ax.grid(axis="x",color=LIGHT["grid"]); ax.set_axisbelow(True)
    ax.set_title(f"Cost to mine one bitcoin — public miners, {LQ} {LY}\nEnergy · other direct · allocated cash SG&A (= L1) · D&A attributable; tick = realized price. * appendix (sub-threshold / hosted)",fontsize=10,loc="left",color=LIGHT["text"])
    ax.legend(handles=[Patch(color=LIGHT["s1"],label="Energy (L0-E)"),Patch(color=LIGHT["s2"],label="Other direct"),Patch(color=LIGHT["s3"],label="Allocated cash SG&A"),Patch(color=LIGHT["s4"],label="D&A attributable"),Line2D([0],[0],color=LIGHT["text"],lw=2,label="Realized price")],loc="lower right",fontsize=8,frameon=False,ncol=5,bbox_to_anchor=(1,-0.18))
    fig.text(0.01,0.005,"Source: SEC filings (10-Q/10-K/6-K), HASHFLOPS Mining Cost Standard v1.0. Not investment advice.",fontsize=7,color=LIGHT["text2"])
    plt.tight_layout(); fig.savefig(f"{OUTD}/cost_stack_{per}.png",facecolor=LIGHT["surface"]); plt.close(fig); print("png ok")
    # TTM chart
    from openpyxl import load_workbook
    wb=load_workbook(xl,data_only=True); ws=wb["TTM"]; tr=[]
    ttm_title=str(ws["A1"].value or "")
    for r in range(4,ws.max_row+1):
        t=ws[f"B{r}"].value; l1=ws[f"N{r}"].value; pr=ws[f"Q{r}"].value; tier=ws[f"C{r}"].value; btc=ws[f"E{r}"].value
        if t and isinstance(l1,(int,float)) and isinstance(pr,(int,float)): tr.append((t,l1,pr,tier,btc))
    tr.sort(key=lambda x:x[1])
    fig,ax=plt.subplots(figsize=(10,0.5*len(tr)+2.0),dpi=160); fig.patch.set_facecolor(LIGHT["surface"]); ax.set_facecolor(LIGHT["surface"])
    ys=list(range(len(tr)))[::-1]
    for (t,l1,pr,tier,btc),yy in zip(tr,ys):
        ax.barh(yy,l1,color=LIGHT["s1"] if tier==1 else LIGHT["s2"],height=0.6); ax.plot([pr,pr],[yy-0.4,yy+0.4],color=LIGHT["text"],linewidth=2)
        ax.text(l1+1200,yy-0.12,f"${l1/1000:.1f}k",fontsize=8,color=LIGHT["text2"])
    ax.set_yticks(ys); ax.set_yticklabels([f"{t}{'' if tier==1 else ' (T2)'}  ·  {btc:,.0f} BTC" for t,l1,pr,tier,btc in tr],fontsize=9)
    ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v,p:f"${v/1000:.0f}k"))
    for sp in ["top","right","left"]: ax.spines[sp].set_visible(False)
    ax.grid(axis="x",color=LIGHT["grid"]); ax.set_axisbelow(True)
    win=ttm_title.split("(")[1].split(")")[0].replace(" + "," · ") if "(" in ttm_title else ""
    ax.set_title(f"L1 cash operating cost per bitcoin — trailing four quarters ({win})\nProduction-weighted (Σ$ ÷ ΣBTC); tick = realized price TTM; blue = Tier 1 owner-operators, orange = Tier 2 hosted",fontsize=10,loc="left",color=LIGHT["text"])
    fig.text(0.01,0.005,"Source: SEC filings (10-Q/10-K/6-K/20-F), HASHFLOPS Mining Cost Standard v1.0. Not investment advice.",fontsize=7,color=LIGHT["text2"])
    plt.tight_layout(); fig.savefig(f"{OUTD}/l1_ttm_{CUT}.png",facecolor=LIGHT["surface"]); plt.close(fig); print("ttm png ok",[(t,round(l1)) for t,l1,pr,tier,btc in tr])
except Exception as e: print("png skipped:",e)
print("rows:",[(r["t"],round(r["l1"]),r["hl"]) for r in rows])
