"""Build Mining_Cost_Standard_v1.0_<cut>.xlsx from normalized.json + overlay_std.py + nav/liquidity_cohort.json.
Data (keyed long table) -> Cost_stack_<period> (formulas via INDEX/MATCH) -> TTM / Ranking / Energy / Bands / Time_series / Liquidity / Checks / Scorecard / Public_Summary."""
import json, sys, os, hashlib, datetime, glob, re
sys.path.insert(0, os.path.dirname(__file__))
from overlay_std import *
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.formatting.rule import ColorScaleRule
from openpyxl.utils import get_column_letter

# Working folder: COST_DIR, else the folder of this script (reproducibility fix 2026-11-15: a hard-coded build path was replaced; logic unchanged)
SP=os.environ.get("COST_DIR") or os.path.dirname(os.path.abspath(__file__))
NORM=f"{SP}/normalized.json" if os.path.exists(f"{SP}/normalized.json") else sorted(__import__("glob").glob(f"{SP}/mining_cost_v1.0_inputs_*.json"))[-1]  # the published inputs file is normalized.json, byte-identical
VERSION="1.0"
N=json.load(open(NORM))
ALL_PERIODS=["Q3_2026","Q2_2026","Q1_2026","Q4_2025","Q3_2025"]
PERIODS=[p for p in ALL_PERIODS if any(p in N[t]["periods"] for t in N)]
LATEST=PERIODS[0]; TTM_PERIODS=PERIODS[:4]            # data cut = latest quarter present; TTM = latest four quarters
LQ,LY=LATEST.split("_"); LATEST_LABEL=f"{LQ} {LY}"; CUT=f"{LY}{LQ}"
OUT=f"{SP}/Mining_Cost_Standard_v{VERSION}_{CUT}.xlsx"
LIQ=json.load(open(f"{SP}/nav/liquidity_cohort.json")) if os.path.exists(f"{SP}/nav/liquidity_cohort.json") else {}
PLABEL={"Q3_2026":"Q3 2026 (Jul–Sep 2026)","Q2_2026":"Q2 2026 (Apr–Jun 2026)","Q1_2026":"Q1 2026 (Jan–Mar 2026)","Q4_2025":"Q4 2025 (Oct–Dec 2025)","Q3_2025":"Q3 2025 (Jul–Sep 2025)"}
PEND={"Q3_2026":"2026-09-30","Q2_2026":"2026-06-30","Q1_2026":"2026-03-31","Q4_2025":"2025-12-31","Q3_2025":"2025-09-30"}
_fd=[N[t]["periods"][LATEST].get("filing_date") for t in N if LATEST in N[t]["periods"] and N[t]["periods"][LATEST].get("filing_date")]
_ft=[t for t in N if LATEST in N[t]["periods"] and N[t]["periods"][LATEST].get("filing_date")==max(_fd)] if _fd else []
CUT_NOTE=f"filings through {max(_fd)} ({', '.join(_ft)})" if _fd else ""
PENDING={t:f"{LATEST_LABEL} not yet filed at the data cut; latest available quarter {PERIODS[1].replace('_',' ')} (see Cost_stack_{PERIODS[1]}); no estimate" for t in N if LATEST not in N[t]["periods"]}
ORDER=["RIOT","MARA","CLSK","HIVE","IREN","CIFR","CORZ","WULF","BTDR","CANG","FUFU","ABTC","BTBT","KEEL","HUT"]
TICKERS=[t for t in ORDER if t in N]
for t in N:
    if t not in TICKERS: TICKERS.append(t)

# ---------- styles ----------
F="Arial"; NAVY="1F3864"
H_FILL=PatternFill("solid",start_color=NAVY); H_FONT=Font(name=F,size=10,bold=True,color="FFFFFF")
SUB_FILL=PatternFill("solid",start_color="D9E1F2"); SUB_FONT=Font(name=F,size=10,bold=True,color=NAVY)
KEY_FILL=PatternFill("solid",start_color="FFF2CC"); FULL_FILL=PatternFill("solid",start_color="E2EFDA"); VAL_FILL=PatternFill("solid",start_color="FFE699"); ENERGY_FILL=PatternFill("solid",start_color="DDEBF7"); BAND_FILL=PatternFill("solid",start_color="EDEDED")
thin=Side(border_style="thin",color="BFBFBF"); B=Border(left=thin,right=thin,top=thin,bottom=thin)
def hdr(c,fill=H_FILL,font=H_FONT): c.fill=fill; c.font=font; c.alignment=Alignment(horizontal="center",vertical="center",wrap_text=True); c.border=B
def tx(ws,addr,v,bold=False,italic=False,wrap=False,align="left",color="000000",size=10,fill=None):
    c=ws[addr]; c.value=v; c.font=Font(name=F,size=size,bold=bold,italic=italic,color=color)
    c.alignment=Alignment(horizontal=align,vertical="top" if wrap else "center",wrap_text=wrap); c.border=B
    if fill: c.fill=fill
    return c
def num(ws,addr,v,fmt,color="0000FF",fill=None,bold=False):
    c=ws[addr]; c.value=v; c.font=Font(name=F,size=10,color=color,bold=bold); c.alignment=Alignment(horizontal="right",vertical="center"); c.number_format=fmt; c.border=B
    if fill: c.fill=fill
    return c
def frm(ws,addr,f,fmt,fill=None,bold=False,green=False):
    c=ws[addr]; c.value=f; c.font=Font(name=F,size=10,color="008000" if green else "000000",bold=bold); c.alignment=Alignment(horizontal="right",vertical="center"); c.number_format=fmt; c.border=B
    if fill: c.fill=fill
    return c
USD='#,##0;(#,##0);"–"'; PB='"$"#,##0;("$"#,##0);"–"'; PCT='0.0%;(0.0%);"–"'; DEC='0.0;(0.0);"–"'; DEC3='0.000;(0.000);"–"'; INT='#,##0;(#,##0);"–"'; USDM='#,##0.0;(#,##0.0);"–"'

def g(t,per,f):
    p=N[t]["periods"].get(per); x=p.get(f) if p else None
    return x.get("value") if isinstance(x,dict) else x
def gx(t,per,f,k):
    p=N[t]["periods"].get(per); x=p.get(f) if p else None
    return (x.get(k) if isinstance(x,dict) else None) or ""
def isnum(v): return isinstance(v,(int,float)) and not isinstance(v,bool)
def comp(t,per):
    p=N[t]["periods"].get(per); return (p["direct_cost_btc_gross"].get("components") or {}) if p else {}

from cost_common import derive_rows
rows=derive_rows(N,PERIODS,TICKERS)

wb=Workbook(); wb.remove(wb.active)

# ===== Data =====
ws=wb.create_sheet("Data"); ws.sheet_view.showGridLines=False; ws.freeze_panes="B4"
tx(ws,"A1","Data — keyed long table (TICKER|PERIOD|METRIC). Every Cost_stack input is pulled from here. Blue = numeric input; Text = non-numeric input.",bold=True,size=12,color=NAVY)
tx(ws,"A2","Source = XBRL concept [dimensions] or verbatim quote (section). Confidence: XBRL = tagged fact; TEXT-2x = text figure confirmed by independent blind re-extraction; TEXT-1x = single extraction; MISMATCH = passes disagree (see Checks).",italic=True,color="595959")
heads=["key","ticker","period","metric","value","text","unit","confidence","source","definition","derivation"]; widths=[36,8,9,24,16,30,9,11,70,70,20]
for i,(h,w) in enumerate(zip(heads,widths)):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c); ws.column_dimensions[get_column_letter(i+1)].width=w
for r,row in enumerate(rows,start=4):
    tx(ws,f"A{r}",row["key"]); tx(ws,f"B{r}",row["ticker"]); tx(ws,f"C{r}",row["period"]); tx(ws,f"D{r}",row["metric"])
    v=row["value"]
    if isnum(v):
        u=row["unit"]; fmt=INT if u in ("BTC","int","MW","MWh") else (DEC3 if u in ("USD/kWh","ratio") else (DEC if u in ("EH/s","J/TH") else USD))
        num(ws,f"E{r}",v,fmt)
    else: tx(ws,f"E{r}","",align="right")
    tx(ws,f"F{r}",row["text"] or ""); tx(ws,f"G{r}",row["unit"]); tx(ws,f"H{r}",row["confidence"] or ""); tx(ws,f"I{r}",row["source"]); tx(ws,f"J{r}",row["definition"]); tx(ws,f"K{r}",row["derivation"])
RAW_LAST=3+len(rows); ws.auto_filter.ref=f"A3:K{RAW_LAST}"
def PULL(t,per,metric,text=False):
    col="F" if text else "E"
    ix=f'INDEX(Data!${col}$4:${col}${RAW_LAST},MATCH("{t}|{per}|{metric}",Data!$A$4:$A${RAW_LAST},0))'
    return f'IFERROR(IF({ix}="","",{ix}),"")'

# ===== Cost_stack per period =====
CS_COLS=[("A","Company",16),("B","Ticker",6),("C","Tier",4),("D","Scope",6),("E","Status",14),
 ("F","BTC mined (denominator)",10),("G","BTC mining revenue, $",13),("H","Total revenue, $",13),("I","BTC revenue share",8),
 ("J","Energy cost, $",12),("K","Energy BTC base",8),("L","ENERGY / BTC, $ (L0-E)",11),
 ("M","Direct cost GROSS, $",13),("N","Credits (curtailment/DR/power sales), $",12),("O","Direct cost NET, $",13),("P","Direct GROSS / BTC, $",10),("Q","Direct NET / BTC, $ (L0)",11),
 ("R","SG&A reported, $",12),("S","SBC in SG&A, $",11),("T","Other non-cash in SG&A, $",10),("U","Non-recurring cash in SG&A, $",11),("V","Cash SG&A run-rate, $",12),("W","Cost-share key",8),
 ("X","Alloc. cash SG&A / BTC (rev-share), $",11),("Y","CASH OPERATING COST / BTC, $ (L1, rev-share)",14),
 ("Z","L1 band: 0% alloc, $",10),("AA","L1 band: cost-share, $",10),("AB","L1 band: 100% alloc, $",10),
 ("AC","Interest expense (P&L), $",12),("AD","Alloc. interest / BTC, $",10),("AE","CASH BUSINESS COST / BTC, $ (L2)",13),
 ("AF","D&A attributable to BTC, $",13),("AG","D&A method",7),("AH","D&A / BTC, $",10),("AI","FULL ACCOUNTING COST / BTC, $ (L3)",13),
 ("AJ","Accelerated D&A in consolidated, $",11),("AK","Run-rate D&A / BTC, $ (ex-accelerated)",11),("AL","FULL run-rate / BTC, $",11),
 ("AM","Realized price / BTC, $ (rev ÷ BTC)",12),("AN","Reported avg price / BTC, $",11),("AO","Cash operating margin",9),("AP","Cash business margin",9),("AQ","Full margin",9),
 ("AR","Cash interest paid 3M, $ (ref.)",11),("AS","Reported cost-to-mine ex-D&A / BTC, $",11),("AT","Δ L0 vs reported",9),("AU","Reported cost incl. D&A / BTC, $",11),("AV","Δ (L0 + D&A) vs reported",9),
 ("AW","Headline (Tier 1 & BTC ≥ threshold)",9)]
CS_LAST_COL="AW"
def build_cost_stack(per):
    ws=wb.create_sheet(f"Cost_stack_{per}"); ws.sheet_view.showGridLines=False; ws.freeze_panes="F6"
    tx(ws,"A1",f"Cost stack — {PLABEL[per]} — strict report-only, XBRL-sourced",bold=True,size=13,color=NAVY)
    tx(ws,"A2","Layers: L0-E energy/BTC → L0 direct NET/BTC → + allocated cash SG&A = L1 CASH OPERATING COST (primary; band 0% / cost-share / rev-share / 100%) → + allocated P&L interest = L2 CASH BUSINESS COST → + D&A attributable = L3 FULL ACCOUNTING COST (and run-rate variant ex-accelerated D&A). Realized price = BTC revenue ÷ BTC mined.",italic=True,color="595959")
    tx(ws,"A3","Green = pulled from Data by key; black = formulas; yellow = headline metrics; blue band = energy layer; grey = allocation band; orange = validation vs company-reported figures. Tier 3 rows: no stack.",italic=True,color="595959")
    bands=[("A","E","Identity",SUB_FILL),("F","I","Production & allocation base",SUB_FILL),("J","L","Energy layer (L0-E)",ENERGY_FILL),("M","Q","Direct mining cost (L0)",SUB_FILL),("R","Y","Overhead layer (L1)",KEY_FILL),("Z","AB","L1 allocation band",BAND_FILL),("AC","AE","Financing layer (L2)",KEY_FILL),("AF","AL","Accounting layer (L3)",FULL_FILL),("AM","AQ","Price & margins",SUB_FILL),("AR","AV","Reference & validation",VAL_FILL),("AW","AW","Flag",SUB_FILL)]
    for a,b,lab,fill in bands:
        c=ws[f"{a}4"]; c.value=lab; hdr(c,fill=fill,font=SUB_FONT)
        if a!=b: ws.merge_cells(f"{a}4:{b}4")
    for col,h,w in CS_COLS:
        c=ws[f"{col}5"]; c.value=h; hdr(c); ws.column_dimensions[col].width=w
    ws.row_dimensions[5].height=64; ws.row_dimensions[4].height=20
    for i,t in enumerate(TICKERS):
        r=6+i
        tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t)
        if per not in N[t]["periods"]:
            tx(ws,f"E{r}","not reported / not extracted",italic=True); continue
        frm(ws,f"C{r}","="+PULL(t,per,"tier"),'0',green=True); frm(ws,f"D{r}","="+PULL(t,per,"scope_code",text=True),'@',green=True); ws[f"D{r}"].alignment=Alignment(horizontal="center")
        frm(ws,f"E{r}","="+PULL(t,per,"status",text=True),'@',green=True); ws[f"E{r}"].alignment=Alignment(horizontal="left")
        frm(ws,f"F{r}","="+PULL(t,per,"btc_mined"),INT,green=True)
        frm(ws,f"G{r}","="+PULL(t,per,"btc_mining_revenue"),USD,green=True); frm(ws,f"H{r}","="+PULL(t,per,"total_revenue"),USD,green=True)
        frm(ws,f"I{r}",f'=IF(AND(ISNUMBER(G{r}),ISNUMBER(H{r}),H{r}<>0),MIN(1,G{r}/H{r}),"")',PCT)
        frm(ws,f"J{r}","="+PULL(t,per,"energy_cost"),USD,green=True,fill=ENERGY_FILL)
        frm(ws,f"K{r}",f'=IF(ISNUMBER({PULL(t,per,"energy_btc_base")}),{PULL(t,per,"energy_btc_base")},F{r})',INT,fill=ENERGY_FILL)
        frm(ws,f"L{r}",f'=IF(AND(C{r}<3,ISNUMBER(J{r}),ISNUMBER(K{r}),K{r}>0),J{r}/K{r},"")',PB,fill=ENERGY_FILL,bold=True)
        frm(ws,f"M{r}","="+PULL(t,per,"direct_cost_gross"),USD,green=True); frm(ws,f"N{r}","="+PULL(t,per,"curtailment_credits"),USD,green=True)
        frm(ws,f"O{r}",f'=IF(ISNUMBER(M{r}),M{r}-IF(ISNUMBER(N{r}),N{r},0),"")',USD)
        frm(ws,f"P{r}",f'=IF(AND(C{r}<3,ISNUMBER(M{r}),ISNUMBER(F{r}),F{r}>0),M{r}/F{r},"")',PB)
        frm(ws,f"Q{r}",f'=IF(AND(C{r}<3,ISNUMBER(O{r}),ISNUMBER(F{r}),F{r}>0),O{r}/F{r},"")',PB,bold=True)
        frm(ws,f"R{r}","="+PULL(t,per,"sga_reported"),USD,green=True); frm(ws,f"S{r}","="+PULL(t,per,"sbc_in_sga"),USD,green=True)
        frm(ws,f"T{r}","="+PULL(t,per,"other_noncash_sga"),USD,green=True); frm(ws,f"U{r}","="+PULL(t,per,"nonrec_cash_sga"),USD,green=True)
        frm(ws,f"V{r}",f'=IF(ISNUMBER(R{r}),R{r}-IF(ISNUMBER(S{r}),S{r},0)-IF(ISNUMBER(T{r}),T{r},0)-IF(ISNUMBER(U{r}),U{r},0),"")',USD)
        frm(ws,f"W{r}","="+PULL(t,per,"cost_share"),DEC3,green=True)
        frm(ws,f"X{r}",f'=IF(AND(C{r}<3,ISNUMBER(V{r}),ISNUMBER(I{r}),ISNUMBER(F{r}),F{r}>0),V{r}*I{r}/F{r},"")',PB)
        frm(ws,f"Y{r}",f'=IF(AND(ISNUMBER(Q{r}),ISNUMBER(X{r})),Q{r}+X{r},"")',PB,fill=KEY_FILL,bold=True)
        frm(ws,f"Z{r}",f'=IF(ISNUMBER(Q{r}),Q{r},"")',PB,fill=BAND_FILL)
        frm(ws,f"AA{r}",f'=IF(AND(ISNUMBER(Q{r}),ISNUMBER(V{r}),ISNUMBER(W{r}),ISNUMBER(F{r}),F{r}>0),Q{r}+V{r}*W{r}/F{r},"")',PB,fill=BAND_FILL)
        frm(ws,f"AB{r}",f'=IF(AND(ISNUMBER(Q{r}),ISNUMBER(V{r}),ISNUMBER(F{r}),F{r}>0),Q{r}+V{r}/F{r},"")',PB,fill=BAND_FILL)
        frm(ws,f"AC{r}","="+PULL(t,per,"interest_expense_pnl"),USD,green=True)
        frm(ws,f"AD{r}",f'=IF(AND(C{r}<3,ISNUMBER(AC{r}),ISNUMBER(I{r}),ISNUMBER(F{r}),F{r}>0),MAX(AC{r},0)*I{r}/F{r},"")',PB)
        frm(ws,f"AE{r}",f'=IF(AND(ISNUMBER(Y{r}),ISNUMBER(AD{r})),Y{r}+AD{r},"")',PB,fill=KEY_FILL,bold=True)
        frm(ws,f"AG{r}","="+PULL(t,per,"da_method",text=True),'@',green=True); ws[f"AG{r}"].alignment=Alignment(horizontal="center")
        dac=PULL(t,per,"da_consolidated")
        frm(ws,f"AF{r}",f'=IF(AG{r}="REV",IF(AND(ISNUMBER({dac}),ISNUMBER(I{r})),{dac}*I{r},""),IF(AG{r}="NA","",{PULL(t,per,"da_btc_attrib")}))',USD)
        frm(ws,f"AH{r}",f'=IF(AND(ISNUMBER(AF{r}),ISNUMBER(F{r}),F{r}>0),AF{r}/F{r},"")',PB)
        frm(ws,f"AI{r}",f'=IF(AND(ISNUMBER(AE{r}),ISNUMBER(AH{r})),AE{r}+AH{r},"")',PB,fill=FULL_FILL,bold=True)
        frm(ws,f"AJ{r}","="+PULL(t,per,"accelerated_da"),USD,green=True)
        acc_rule=PULL(t,per,"accelerated_da",text=True)
        frm(ws,f"AK{r}",f'=IF(ISNUMBER(AH{r}),IF(ISNUMBER(AJ{r}),IF({acc_rule}="REV",(AF{r}-AJ{r}*I{r})/F{r},IF({acc_rule}="True",(AF{r}-AJ{r})/F{r},AH{r})),AH{r}),"")',PB)
        frm(ws,f"AL{r}",f'=IF(AND(ISNUMBER(AE{r}),ISNUMBER(AK{r})),AE{r}+AK{r},"")',PB,fill=FULL_FILL)
        frm(ws,f"AM{r}",f'=IF(AND(ISNUMBER(G{r}),ISNUMBER(F{r}),F{r}>0),G{r}/F{r},"")',PB,bold=True)
        frm(ws,f"AN{r}","="+PULL(t,per,"rep_price_per_btc"),PB,green=True)
        frm(ws,f"AO{r}",f'=IF(AND(ISNUMBER(AM{r}),ISNUMBER(Y{r}),AM{r}>0),(AM{r}-Y{r})/AM{r},"")',PCT)
        frm(ws,f"AP{r}",f'=IF(AND(ISNUMBER(AM{r}),ISNUMBER(AE{r}),AM{r}>0),(AM{r}-AE{r})/AM{r},"")',PCT)
        frm(ws,f"AQ{r}",f'=IF(AND(ISNUMBER(AM{r}),ISNUMBER(AI{r}),AM{r}>0),(AM{r}-AI{r})/AM{r},"")',PCT)
        frm(ws,f"AR{r}","="+PULL(t,per,"cash_interest_paid_3m"),USD,green=True)
        frm(ws,f"AS{r}","="+PULL(t,per,"rep_cost_ex_da_per_btc"),PB,green=True,fill=VAL_FILL)
        frm(ws,f"AT{r}",f'=IF(AND(ISNUMBER(AS{r}),ISNUMBER(Q{r})),Q{r}-AS{r},"")',PB,fill=VAL_FILL)
        frm(ws,f"AU{r}","="+PULL(t,per,"rep_cost_incl_da_per_btc"),PB,green=True,fill=VAL_FILL)
        frm(ws,f"AV{r}",f'=IF(AND(ISNUMBER(AU{r}),ISNUMBER(Q{r}),ISNUMBER(AH{r})),Q{r}+AH{r}-AU{r},"")',PB,fill=VAL_FILL)
        frm(ws,f"AW{r}",f'=IF(AND(C{r}=1,ISNUMBER(F{r}),F{r}>=Standard!$C$4,ISNUMBER(Y{r})),"HEADLINE",IF(ISNUMBER(Y{r}),"appendix","n/c"))','@')
        ws.row_dimensions[r].height=18
    last=5+len(TICKERS)
    for col in ["L","Q","Y","AE","AI"]:
        ws.conditional_formatting.add(f"{col}6:{col}{last}",ColorScaleRule(start_type='min',start_color='63BE7B',mid_type='percentile',mid_value=50,mid_color='FFEB84',end_type='max',end_color='F8696B'))
    for col in ["AO","AP","AQ"]:
        ws.conditional_formatting.add(f"{col}6:{col}{last}",ColorScaleRule(start_type='num',start_value=-0.5,start_color='F8696B',mid_type='num',mid_value=0,mid_color='FFEB84',end_type='num',end_value=0.5,end_color='63BE7B'))
    nr=last+2
    notes=["Scope codes: E energy only • E+S energy + site opex • E+S* partial site scope • E+S+H incl. third-party hosting • H hosted • H-RP related-party hosted • N/S not separable • N/D not disclosed.",
     "L0-E energy layer: electricity/power component of BTC-mining cost of revenue, gross of credits. MARA: owned-site purchased energy ÷ owned-site BTC (column K override) — comparable to MARA's reported energy cost per BTC. Blank where the filing does not split electricity (CIFR, ABTC, HUT, CANG).",
     "Direct NET = GROSS − disclosed curtailment / demand-response / power-sale credits (RIOT, WULF, CIFR). Denominator adjustments (MARA ex-ADGM; BTDR cost incl. co-mining) are documented in Data (metrics btc_mined / direct_cost_gross).",
     "Cash SG&A run-rate = reported SG&A − SBC in SG&A − other disclosed non-cash − disclosed non-recurring cash items. L1 = Direct NET/BTC + cash SG&A × BTC revenue share ÷ BTC. Band: 0% (direct only), cost-share key (BTC CoR ÷ total CoR), rev-share (primary), 100%.",
     "L2 adds P&L interest expense × revenue share (accrual; cash coupons are semi-annual and lumpy — cash paid shown for reference). Capital-structure dependent; CIFR/WULF/CORZ carry HPC-project debt.",
     "D&A method: SEG miner-class/segment D&A disclosed • DER derived from company-reported cost-to-mine incl. vs ex-D&A • REV consolidated D&A × revenue share (flagged) • NA. Run-rate variant removes disclosed accelerated depreciation (rule per Data: REV → × revenue share; True → fully inside attributable figure).",
     "Validation: AT compares L0 with the company's own ex-D&A cost-to-mine; AV compares L0 + D&A/BTC with the incl-D&A metric. Residuals reflect definitional scope (CLSK energy-only; RIOT incl. site opex; WULF net of DR)."]
    for i,n_ in enumerate(notes):
        tx(ws,f"A{nr+i}",n_,wrap=True); ws.merge_cells(f"A{nr+i}:{CS_LAST_COL}{nr+i}"); ws.row_dimensions[nr+i].height=28
for per in PERIODS: build_cost_stack(per)
ROW={t:6+i for i,t in enumerate(TICKERS)}

# ===== Standard (rules + parameters) =====
ws=wb.create_sheet("Standard"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Mining Cost Standard v1.0 — rules and parameters",bold=True,size=13,color=NAVY)
ws.column_dimensions["A"].width=34; ws.column_dimensions["B"].width=18; ws.column_dimensions["C"].width=16; ws.column_dimensions["D"].width=90
tx(ws,"A3","Parameter",bold=True,fill=SUB_FILL); tx(ws,"B3","Unit",bold=True,fill=SUB_FILL); tx(ws,"C3","Value",bold=True,fill=SUB_FILL); tx(ws,"D3","Source / rationale",bold=True,fill=SUB_FILL)
tx(ws,"A4","Headline materiality threshold"); tx(ws,"B4","BTC mined / quarter"); num(ws,"C4",MATERIALITY_BTC,INT); tx(ws,"D4","Companies below this production are shown in the appendix table: per-BTC metrics on small volumes are dominated by fixed costs and one-offs.",wrap=True)
tx(ws,"A5","BTC spot at data cut (liquidity layer only)"); tx(ws,"B5","USD/BTC"); num(ws,"C5",BTC_SPOT[0],PB); tx(ws,"D5",BTC_SPOT[1]+" ("+BTC_SPOT[2]+"). Used only to value BTC holdings on the Liquidity sheet; cost layers use filing facts exclusively.",wrap=True)
tx(ws,"A6","Days in quarter (for $/PH/day)"); tx(ws,"B6","days"); num(ws,"C6",91,INT); tx(ws,"D6","Q2/Q3 = 91–92; indicative only.",wrap=True)
rules=[("Scope & tiers","Tier 1 owner-operators with a computable stack; Tier 2 hosted cost base (ABTC related-party; BTBT immaterial); Tier 3 mining cost not separable/disclosed (KEEL, HUT). HUT is excluded from cohort sums (consolidates ABTC)."),
("Periods","Calendar quarters. Fiscal mappings: CLSK FQ = cal Q−1 shift (FQ3 FY26 = Q2 2026; FQ4 FY26 = Q3 2026 from the 10-K, 12M − 9M); IREN FQ4 FY26 = Q2 2026 (12M−9M), FQ1 FY27 = Q3 2026; HIVE FQ1 FY27 = Q2 2026, FQ2 FY27 = Q3 2026. Q4 for calendar filers = 10-K 12M − 9M from the Q3 10-Q. A company whose latest quarter is not filed at the data cut is PENDING (no estimate, no carry-forward)."),
("Sources","SEC EDGAR only: XBRL instance facts (incl. segment dimensions) + primary-document text for MD&A KPIs; 6-K releases/interims for FPIs (BTDR, CANG, FUFU; HIVE before its 10-K). No analyst data, no price feeds in the cost layers."),
("L0-E energy layer","Electricity/power component of BTC-mining cost of revenue, gross of credits, ÷ BTC mined (owned-site BTC where the energy figure covers owned sites only). The most comparable layer across companies."),
("L0 direct cost","Segment cost of revenue excl. D&A as booked, gross of credits; credits shown separately; NET = GROSS − credits. Only filing-enabled adjustments (CORZ segment D&A stripped; BTDR 'Depreciation and SBC' stripped; WULF DR grossed up). Scope code records what the line contains."),
("L1 cash operating cost (PRIMARY)","L0 NET/BTC + cash SG&A run-rate × BTC revenue share ÷ BTC. Cash SG&A run-rate excludes SBC in SG&A, other disclosed non-cash items and disclosed non-recurring cash items. Band published: 0% / cost-share / rev-share / 100%."),
("L2 cash business cost","L1 + P&L interest expense (accrual, net of capitalized) × revenue share ÷ BTC; negative net interest floored at zero. Secondary: capital-structure dependent."),
("L3 full accounting cost","L2 + D&A attributable ÷ BTC. D&A hierarchy SEG → DER → REV → NA. Run-rate variant removes disclosed accelerated depreciation."),
("Price & margins","Realized price = BTC mining revenue ÷ BTC mined (ASC 606 net of pool fees). Margins per layer. Sensitivity grid uses hypothetical BTC prices against reported cost levels (indicative — costs are themselves price-dependent via curtailment)."),
("TTM","Trailing four quarters summed in dollars and BTC, then divided (production-weighted); only where all four quarters are available for the company."),
("Verification","(1) LibreOffice recalc, zero formula errors; (2) independent Python engine recomputes every derived cell; (3) blind second-pass re-extraction of text-sourced inputs (Q1–Q3 2026) → confidence flags; Q3–Q4 2025 inputs are single-pass (XBRL-tagged where available) and feed only the TTM/time-series layers; (4) reconciliation to company-reported cost-to-mine and price metrics; (5) arithmetic integrity (components, segment sums, YTD − prior YTD)."),
("Publication","Public Summary (EN) is the only published narrative; no recommendations; versioning Mining_Cost_Standard_v<standard>_<cut>.xlsx; errata via patch release; reproducibility package with SHA-256 of inputs.")]
r0=9; tx(ws,f"A{r0-1}","Rule",bold=True,fill=SUB_FILL); tx(ws,f"B{r0-1}","",fill=SUB_FILL); tx(ws,f"C{r0-1}","",fill=SUB_FILL); tx(ws,f"D{r0-1}","Definition",bold=True,fill=SUB_FILL)
for i,(a,b) in enumerate(rules):
    r=r0+i; tx(ws,f"A{r}",a,bold=True,wrap=True); tx(ws,f"D{r}",b,wrap=True); ws.merge_cells(f"A{r}:C{r}"); ws.row_dimensions[r].height=max(32,15*(len(b)//95+1))

# ===== TTM =====
ws=wb.create_sheet("TTM"); ws.sheet_view.showGridLines=False
tx(ws,"A1",f"Trailing four quarters ({' + '.join(TTM_PERIODS)}) — production-weighted per-BTC metrics (only where all four quarters are available)",bold=True,size=13,color=NAVY)
th=["Company","Ticker","Tier","Quarters with L1 computable","BTC mined TTM","BTC revenue TTM, $","Energy TTM, $","Direct NET TTM, $","Cash SG&A alloc TTM, $","Interest alloc TTM, $","D&A attrib TTM, $","ENERGY/BTC TTM","L0 Direct NET/BTC TTM","L1 CASH OPERATING/BTC TTM","L2 CASH BUSINESS/BTC TTM","L3 FULL/BTC TTM","Realized price TTM","Cash op. margin TTM","Full margin TTM"]
for i,h in enumerate(th):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c); ws.column_dimensions[get_column_letter(i+1)].width=12
ws.column_dimensions["A"].width=18; ws.row_dimensions[3].height=55
def sum4(col,r,needall=True):
    cells=[f"Cost_stack_{p}!{col}{r}" for p in TTM_PERIODS]
    cond="AND("+",".join(f"ISNUMBER({c})" for c in cells)+")"
    return f'=IF({cond},{"+".join(cells)},"")'
def sum4_alloc(valcol,sharecol,r):
    terms=[f"Cost_stack_{p}!{valcol}{r}*Cost_stack_{p}!{sharecol}{r}" for p in TTM_PERIODS]
    cond="AND("+",".join(f"ISNUMBER(Cost_stack_{p}!{valcol}{r}),ISNUMBER(Cost_stack_{p}!{sharecol}{r})" for p in TTM_PERIODS)+")"
    return f'=IF({cond},{"+".join(terms)},"")'
for i,t in enumerate(TICKERS):
    r=4+i; s=ROW[t]
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t); num(ws,f"C{r}",TIER[t],'0',color="000000")
    frm(ws,f"D{r}","="+"+".join(f'IF(ISNUMBER(Cost_stack_{p}!Y{s}),1,0)' for p in TTM_PERIODS),'0')
    frm(ws,f"E{r}",sum4("F",s),INT,green=True); frm(ws,f"F{r}",sum4("G",s),USD,green=True); frm(ws,f"G{r}",sum4("J",s),USD,green=True); frm(ws,f"H{r}",sum4("O",s),USD,green=True)
    frm(ws,f"I{r}",sum4_alloc("V","I",s),USD,green=True); frm(ws,f"J{r}",sum4_alloc("AC","I",s),USD,green=True)
    frm(ws,f"K{r}",sum4("AF",s),USD,green=True)
    # energy base: sum of K across periods
    frm(ws,f"L{r}","=0",PB)  # overwritten below
    frm(ws,f"M{r}",f'=IF(AND(C{r}<3,ISNUMBER(H{r}),ISNUMBER(E{r}),E{r}>0),H{r}/E{r},"")',PB)
    frm(ws,f"N{r}",f'=IF(AND(ISNUMBER(M{r}),ISNUMBER(I{r})),M{r}+I{r}/E{r},"")',PB,fill=KEY_FILL,bold=True)
    frm(ws,f"O{r}",f'=IF(AND(ISNUMBER(N{r}),ISNUMBER(J{r})),N{r}+J{r}/E{r},"")',PB)
    frm(ws,f"P{r}",f'=IF(AND(ISNUMBER(O{r}),ISNUMBER(K{r})),O{r}+K{r}/E{r},"")',PB,fill=FULL_FILL)
    frm(ws,f"Q{r}",f'=IF(AND(ISNUMBER(F{r}),ISNUMBER(E{r}),E{r}>0),F{r}/E{r},"")',PB)
    frm(ws,f"R{r}",f'=IF(AND(ISNUMBER(Q{r}),ISNUMBER(N{r}),Q{r}>0),(Q{r}-N{r})/Q{r},"")',PCT); frm(ws,f"S{r}",f'=IF(AND(ISNUMBER(Q{r}),ISNUMBER(P{r}),Q{r}>0),(Q{r}-P{r})/Q{r},"")',PCT)
# fix L formula cleanly (energy TTM / sum of energy BTC base)
for i,t in enumerate(TICKERS):
    r=4+i; s=ROW[t]
    kcells=[f"Cost_stack_{p}!K{s}" for p in TTM_PERIODS]
    cond="AND("+",".join(f"ISNUMBER({c})" for c in kcells)+")"
    ws[f"L{r}"].value=f'=IF(AND(C{r}<3,ISNUMBER(G{r}),{cond}),G{r}/({"+".join(kcells)}),"")'
    # interest alloc with floor at zero: rebuild J
    jt=[f"MAX(Cost_stack_{p}!AC{s},0)*Cost_stack_{p}!I{s}" for p in TTM_PERIODS]
    jc="AND("+",".join(f"ISNUMBER(Cost_stack_{p}!AC{s}),ISNUMBER(Cost_stack_{p}!I{s})" for p in TTM_PERIODS)+")"
    ws[f"J{r}"].value=f'=IF({jc},{"+".join(jt)},"")'
TTM_LAST=3+len(TICKERS)
tx(ws,f"A{TTM_LAST+2}","TTM metrics are production-weighted (sum of dollars ÷ sum of BTC), so quarters with higher output weigh more. Blank where any quarter is missing or the company is Tier 3.",italic=True,color="595959"); ws.merge_cells(f"A{TTM_LAST+2}:S{TTM_LAST+2}")

# ===== Ranking =====
ws=wb.create_sheet("Ranking"); ws.sheet_view.showGridLines=False
CS=f"Cost_stack_{LATEST}"
tx(ws,"A1",f"Ranking — {LATEST_LABEL} headline set (Tier 1, BTC mined ≥ materiality threshold) by L1 CASH OPERATING COST / BTC",bold=True,size=13,color=NAVY)
tx(ws,"A2",f"Rank is by rev-share L1; the band columns show how much the rank depends on the overhead allocation key. L2/L3 are secondary. Sensitivity: cash operating margin at hypothetical BTC prices against {LQ} cost levels. Companies whose {LATEST_LABEL} report was not filed at the data cut are listed as PENDING (no estimate).",italic=True,color="595959")
rh=["Rank","Company","Ticker","Scope","L0-E Energy/BTC","L0 Direct NET/BTC","L1 CASH OPERATING/BTC","L1 band 0%","L1 band cost-share","L1 band 100%","L2 CASH BUSINESS/BTC","L3 FULL/BTC","L3 run-rate/BTC",f"Realized price {LQ}",f"Cash op. margin {LQ}","L1 TTM","@ $50k","@ $60k","@ $70k","@ $80k","@ $90k","@ $100k","Headline?","Comparability flag"]
for i,h in enumerate(rh):
    c=ws.cell(row=4,column=i+1,value=h); hdr(c)
for i,w in enumerate([5,18,6,6,11,11,13,10,10,10,12,11,11,11,9,11,8,8,8,8,8,8,9,60]): ws.column_dimensions[get_column_letter(i+1)].width=w
ws.row_dimensions[4].height=50
FLAGS={"RIOT":"E+S scope; DER D&A; rev share ~65% → moderate allocation sensitivity",
 "MARA":"E+S+H scope (~30–50% of BTC hosted at third parties); denominator ex-ADGM; REV D&A (accelerated depreciation removed in the run-rate L3 where disclosed); non-recurring G&A items excluded",
 "CLSK":"E scope — site labor outside direct cost (in payroll): L0 understated vs E+S peers; L1 comparable (100% allocation)",
 "HIVE":"E+S scope; REV D&A; SBC separate line → clean cash SG&A",
 "IREN":"E+S* scope; BTC revenue share falling fast (49% Q2 → 12% Q3 2026) as AI Cloud scales and mining is decommissioned; allocated overhead likely overstated; REV D&A HIGH uncertainty; filing rounded to $1m from Q1 FY27; sub-threshold from Q3 2026",
 "CIFR":"E+S scope; two segments from Q3 2026 (rev share 100% → 78%); HPC-construction interest allocated by revenue share → L2 not comparable; segment D&A from Q3 2026; operational KPIs only from the 8-K investor deck",
 "CORZ":"E+S scope; self-mining minority and winding down (fleet held for sale); SEG D&A (mostly infrastructure once miners stop depreciating); small volume",
 "WULF":"E scope (electricity only, grossed for DR); small volume; DER D&A incl. accelerated; mining marginal next to HPC leasing",
 "BTDR":"E+S scope incl. co-mining (cost and BTC aligned); 6-K; SBC not deducted (conservative); REV D&A",
 "CANG":"H scope (Tier 2): all-in third-party hosting fees, electricity embedded → no energy layer; direct cost = reported cash cost/BTC × BTC (20-F cross-check); SEG D&A (mining machines)", "FUFU":"Tier 3: cost of revenues by counterparty, self-mining not separable → no stack; production and realized price only"}
t1=[t for t in TICKERS if TIER[t]==1]
for i,t in enumerate(t1):
    r=5+i; s=ROW[t]; tr=4+TICKERS.index(t)
    if t in PENDING:
        tx(ws,f"B{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"C{r}",t); tx(ws,f"D{r}","—",align="center"); tx(ws,f"W{r}","PENDING",align="center"); tx(ws,f"X{r}",PENDING[t],wrap=True,italic=True); ws.row_dimensions[r].height=30; continue
    tx(ws,f"B{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"C{r}",t); frm(ws,f"D{r}",f"={CS}!D{s}",'@',green=True)
    frm(ws,f"E{r}",f"={CS}!L{s}",PB,green=True); frm(ws,f"F{r}",f"={CS}!Q{s}",PB,green=True); frm(ws,f"G{r}",f"={CS}!Y{s}",PB,green=True,fill=KEY_FILL,bold=True)
    frm(ws,f"H{r}",f"={CS}!Z{s}",PB,green=True); frm(ws,f"I{r}",f"={CS}!AA{s}",PB,green=True); frm(ws,f"J{r}",f"={CS}!AB{s}",PB,green=True)
    frm(ws,f"K{r}",f"={CS}!AE{s}",PB,green=True); frm(ws,f"L{r}",f"={CS}!AI{s}",PB,green=True); frm(ws,f"M{r}",f"={CS}!AL{s}",PB,green=True)
    frm(ws,f"N{r}",f"={CS}!AM{s}",PB,green=True); frm(ws,f"O{r}",f"={CS}!AO{s}",PCT,green=True); frm(ws,f"P{r}",f"=TTM!N{tr}",PB,green=True)
    for j,pz in enumerate([50000,60000,70000,80000,90000,100000]):
        col=get_column_letter(17+j); frm(ws,f"{col}{r}",f'=IF(ISNUMBER(G{r}),({pz}-G{r})/{pz},"")',PCT)
    frm(ws,f"W{r}",f"={CS}!AW{s}",'@',green=True); tx(ws,f"X{r}",FLAGS.get(t,TIER_NOTE[t]),wrap=True); ws.row_dimensions[r].height=30
lastr=4+len(t1)
for i,t in enumerate(t1):
    r=5+i; frm(ws,f"A{r}",f'=IF(W{r}="HEADLINE",COUNTIFS($W$5:$W${lastr},"HEADLINE",$G$5:$G${lastr},"<"&G{r})+1,"–")','0')
ws.conditional_formatting.add(f"G5:G{lastr}",ColorScaleRule(start_type='min',start_color='63BE7B',mid_type='percentile',mid_value=50,mid_color='FFEB84',end_type='max',end_color='F8696B'))
ws.conditional_formatting.add(f"O5:V{lastr}",ColorScaleRule(start_type='num',start_value=-0.5,start_color='F8696B',mid_type='num',mid_value=0,mid_color='FFEB84',end_type='num',end_value=0.5,end_color='63BE7B'))
sr=lastr+2
tx(ws,f"B{sr}",f"Cohort statistics — HEADLINE set, {LATEST_LABEL}",bold=True,color=NAVY)
hl=f'$W$5:$W${lastr}'
tx(ws,f"B{sr+1}","Production-weighted L1 (Σ cash operating cost $ ÷ Σ BTC)"); frm(ws,f"G{sr+1}",f'=IFERROR(SUMPRODUCT(($W$5:$W${lastr}="HEADLINE")*N(+$G$5:$G${lastr})*N(+{CS}!$F$6:$F${5+len(TICKERS)}))/SUMPRODUCT(($W$5:$W${lastr}="HEADLINE")*N(+{CS}!$F$6:$F${5+len(TICKERS)})),"")',PB)
# the above mixes ranges of different sizes if t1 != TICKERS; implement weighted via helper columns instead
ws[f"G{sr+1}"].value=None
# helper columns Z (BTC) and AA (cost$) for headline rows
for i,t in enumerate(t1):
    r=5+i; s=ROW[t]
    frm(ws,f"Z{r}",f'=IF(W{r}="HEADLINE",{CS}!F{s},0)',INT); frm(ws,f"AA{r}",f'=IF(AND(W{r}="HEADLINE",ISNUMBER(G{r})),G{r}*{CS}!F{s},0)',USD)
    frm(ws,f"AB{r}",f'=IF(AND(W{r}="HEADLINE",ISNUMBER({CS}!G{s})),{CS}!G{s},0)',USD)
    frm(ws,f"AC{r}",f'=IF(AND(W{r}="HEADLINE",ISNUMBER(G{r})),G{r},"")',PB)
ws.column_dimensions["AC"].width=12; tx(ws,"AC4","helper: L1 (headline only)",italic=True,color="595959")
ws.column_dimensions["Z"].width=10; ws.column_dimensions["AA"].width=14; ws.column_dimensions["AB"].width=14
tx(ws,"Z4","helper: BTC (headline)",italic=True,color="595959"); tx(ws,"AA4","helper: L1 × BTC",italic=True,color="595959"); tx(ws,"AB4","helper: BTC revenue",italic=True,color="595959")
frm(ws,f"G{sr+1}",f'=IFERROR(SUM(AA5:AA{lastr})/SUM(Z5:Z{lastr}),"")',PB,bold=True,fill=KEY_FILL)
tx(ws,f"B{sr+2}","Production-weighted realized price"); frm(ws,f"G{sr+2}",f'=IFERROR(SUM(AB5:AB{lastr})/SUM(Z5:Z{lastr}),"")',PB)
tx(ws,f"B{sr+3}","Cohort cash operating margin"); frm(ws,f"G{sr+3}",f'=IFERROR((G{sr+2}-G{sr+1})/G{sr+2},"")',PCT)
tx(ws,f"B{sr+4}","Median L1 (headline)"); frm(ws,f"G{sr+4}",f'=IFERROR(MEDIAN(AC5:AC{lastr}),"")',PB)
tx(ws,f"B{sr+5}","Min / Max L1 (headline)"); frm(ws,f"G{sr+5}",f'=IFERROR(MIN(AC5:AC{lastr}),"")',PB); frm(ws,f"H{sr+5}",f'=IFERROR(MAX(AC5:AC{lastr}),"")',PB)
tx(ws,f"B{sr+6}","Headline companies / Σ BTC"); frm(ws,f"G{sr+6}",f'=COUNTIF($W$5:$W${lastr},"HEADLINE")','0'); frm(ws,f"H{sr+6}",f'=SUM(Z5:Z{lastr})',INT)
tx(ws,f"B{sr+8}",f"Appendix — Tier 2 (hosted) and sub-threshold Tier 1 are listed above with Headline? ≠ HEADLINE; Tier 3 (KEEL, HUT, FUFU) have no stack (see Cost_stack). PENDING = {LATEST_LABEL} report not filed at the data cut: "+(", ".join(sorted(PENDING)) or "none")+".",italic=True,color="595959"); ws.merge_cells(f"B{sr+8}:X{sr+8}")
RANK_STATS_ROW=sr+1

# ===== Energy_layer =====
ws=wb.create_sheet("Energy_layer"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Energy layer (L0-E) — electricity cost per BTC and disclosed power KPIs, by quarter",bold=True,size=13,color=NAVY)
tx(ws,"A2","Energy is the most consistently disclosed cost component; this layer is the cleanest cross-company comparison. $/kWh and MWh are shown with their verbatim definitions on Operational_layer.",italic=True,color="595959")
eh=["Company","Ticker"]+[f"Energy/BTC {p}" for p in PERIODS]+[f"$/kWh {p}" for p in PERIODS]+["Energy/BTC TTM",f"Reported energy/BTC {LQ} (company)","Δ vs reported"]
for i,h in enumerate(eh):
    c=ws.cell(row=4,column=i+1,value=h); hdr(c); ws.column_dimensions[get_column_letter(i+1)].width=11
ws.column_dimensions["A"].width=18; ws.row_dimensions[4].height=40
for i,t in enumerate(TICKERS):
    r=5+i; s=ROW[t]; tr=4+TICKERS.index(t)
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t)
    for j,p in enumerate(PERIODS):
        frm(ws,f"{get_column_letter(3+j)}{r}",f'=IF(Cost_stack_{p}!L{s}="","",Cost_stack_{p}!L{s})',PB,green=True)
        frm(ws,f"{get_column_letter(3+len(PERIODS)+j)}{r}","="+PULL(t,p,"kwh"),DEC3,green=True)
    cE=get_column_letter(3+2*len(PERIODS)); cR=get_column_letter(4+2*len(PERIODS)); cD=get_column_letter(5+2*len(PERIODS))
    frm(ws,f"{cE}{r}",f"=TTM!L{tr}",PB,green=True,fill=KEY_FILL); frm(ws,f"{cR}{r}","="+PULL(t,LATEST,"rep_energy_per_btc"),PB,green=True,fill=VAL_FILL)
    frm(ws,f"{cD}{r}",f'=IF(AND(ISNUMBER(C{r}),ISNUMBER({cR}{r})),C{r}-{cR}{r},"")',PB,fill=VAL_FILL)
ws.conditional_formatting.add(f"C5:{get_column_letter(2+len(PERIODS))}{4+len(TICKERS)}",ColorScaleRule(start_type='min',start_color='63BE7B',mid_type='percentile',mid_value=50,mid_color='FFEB84',end_type='max',end_color='F8696B'))

# ===== Time_series =====
ws=wb.create_sheet("Time_series"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Time series — key metrics by quarter (oldest → newest)",bold=True,size=13,color=NAVY)
PER_ASC=list(reversed(PERIODS))
metrics=[("BTC mined","F",INT),("Realized price / BTC","AM",PB),("L0-E Energy / BTC","L",PB),("L0 Direct NET / BTC","Q",PB),("L1 Cash operating / BTC","Y",PB),("L3 Full / BTC","AI",PB),("Cash operating margin","AO",PCT),("Hashrate end (EH/s)","",DEC)]
col=1
tx(ws,"A3","Company",bold=True,fill=SUB_FILL); tx(ws,"B3","Ticker",bold=True,fill=SUB_FILL)
c=3
for lab,colref,fmt in metrics:
    for p in PER_ASC:
        cell=ws.cell(row=3,column=c,value=f"{lab}\n{p.replace('_',' ')}"); hdr(cell); ws.column_dimensions[get_column_letter(c)].width=10; c+=1
ws.row_dimensions[3].height=45; ws.column_dimensions["A"].width=18
for i,t in enumerate(TICKERS):
    r=4+i; s=ROW[t]; tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t); c=3
    for lab,colref,fmt in metrics:
        for p in PER_ASC:
            if colref: frm(ws,f"{get_column_letter(c)}{r}",f'=IF(Cost_stack_{p}!{colref}{s}="","",Cost_stack_{p}!{colref}{s})',fmt,green=True)
            else: frm(ws,f"{get_column_letter(c)}{r}","="+PULL(t,p,"hashrate_end"),fmt,green=True)
            c+=1
tx(ws,f"A{5+len(TICKERS)}","Hashrate 'end' definitions differ by company (deployed / energized / installed / operating / nameplate) — within-company trend only.",italic=True,color="595959")

# ===== Liquidity =====
ws=wb.create_sheet("Liquidity"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Liquidity & treasury at 2026-06-30 — balance-sheet facts shared with the Mining NAV Standard v1.1 data set (same filings, same source IDs)",bold=True,size=13,color=NAVY)
tx(ws,"A2","Debt = principal of instruments outstanding at the balance-sheet date (carrying amount where principal is not disclosed — flagged in the instrument list; post-balance-sheet issues/repayments excluded; see NAV standard for pro forma). BTC valued at the Standard!C5 spot — the only non-filing input in this workbook.",italic=True,color="595959")
if not LIQ:
    # Liquidity block extracted from the latest-quarter filings themselves (balance sheet, debt note, crypto-asset note)
    for t in TICKERS:
        p=N[t]["periods"].get(LATEST); ex=(p or {}).get("_extra") or {}
        def _xv(k):
            x=ex.get(k); return x.get("value") if isinstance(x,dict) else x
        cash=_xv("cash_and_equivalents")
        if not p or not isnum(cash): continue
        di=_xv("debt_instruments") or []
        # principal where disclosed; otherwise the carrying amount, labelled (BTDR's 6-K release gives balance-sheet carrying amounts only)
        inst=[((str(d.get("instrument") or "")+("" if isnum(d.get("principal")) else " [carrying; principal n/d]")),((d.get("principal") if isnum(d.get("principal")) else (d.get("carrying") or 0)))/1e6) for d in di if isinstance(d,dict)]
        LIQ[t]={"bs_date":PEND[LATEST],"cash":cash/1e6,"restricted_cash":(_xv("restricted_cash")/1e6 if isnum(_xv("restricted_cash")) else None),"btc_count":g(t,LATEST,"btc_holdings_end"),
                "btc_pledged":(_xv("btc_pledged") if isnum(_xv("btc_pledged")) else None),"debt_instruments":inst,"total_equity":(_xv("total_equity")/1e6 if isnum(_xv("total_equity")) else None),
                "filing_url":p.get("url"),"sources":{f"{p.get('form')} {p.get('accession')}":{"date":p.get("filing_date"),"title":f"{LATEST_LABEL} balance sheet, debt and crypto-asset notes ({(ex.get('debt_instruments') or {}).get('source','') if isinstance(ex.get('debt_instruments'),dict) else ''})"[:200],"url":p.get("url")}}}
    LIQ_SOURCE_NOTE=f"Source: the {LATEST_LABEL} filings themselves (balance sheet, debt note, crypto-asset note), extracted alongside the cost inputs; each field with a filing citation on the Data sheet (_extra)."
else: LIQ_SOURCE_NOTE="Source: Mining NAV Standard v1.1 inputs (2026-10-15), each field with filing line reference."
lh=["Company","Ticker","Balance-sheet date","Cash & equivalents, $m","Restricted cash, $m","BTC held","of which pledged/loaned","Debt principal, $m","Total equity, $m","BTC value at spot, $m","Cash + BTC, $m","Net debt (debt − cash − BTC), $m",f"{LQ} cash operating cost, $m (L1 × BTC)","Quarters of L1 covered by cash",f"Debt / {LQ} BTC revenue annualized (×)","Source filing","Debt instruments (principal $m)"]
for i,h in enumerate(lh):
    c=ws.cell(row=4,column=i+1,value=h); hdr(c)
for i,w in enumerate([18,6,11,11,10,9,10,11,11,11,11,13,13,10,11,50,80]): ws.column_dimensions[get_column_letter(i+1)].width=w
ws.row_dimensions[4].height=55
for i,t in enumerate(TICKERS):
    r=5+i; s=ROW[t]; L=LIQ.get(t)
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t)
    if not L: tx(ws,f"C{r}","not extracted" if t not in PENDING else "PENDING (no filing)",italic=True); continue
    tx(ws,f"C{r}",L["bs_date"]); num(ws,f"D{r}",L["cash"],USDM); num(ws,f"E{r}",L["restricted_cash"] if isnum(L["restricted_cash"]) else None,USDM); num(ws,f"F{r}",L["btc_count"],INT); num(ws,f"G{r}",L["btc_pledged"] if isnum(L["btc_pledged"]) else None,INT)
    princ=sum((x[1] or 0) for x in L["debt_instruments"] if isnum(x[1]) and not str(x[0]).startswith("[") and not str(x[0]).upper().startswith("MEMO") and not str(x[0]).startswith("No borrowings"))
    num(ws,f"H{r}",round(princ,3),USDM); num(ws,f"I{r}",L["total_equity"],USDM)
    frm(ws,f"J{r}",f'=IF(ISNUMBER(F{r}),F{r}*Standard!$C$5/1000000,"")',USDM); frm(ws,f"K{r}",f'=IF(AND(ISNUMBER(D{r}),ISNUMBER(J{r})),D{r}+J{r},"")',USDM)
    frm(ws,f"L{r}",f'=IF(AND(ISNUMBER(H{r}),ISNUMBER(K{r})),H{r}-K{r},"")',USDM)
    frm(ws,f"M{r}",f'=IF(AND(ISNUMBER({CS}!Y{s}),ISNUMBER({CS}!F{s})),{CS}!Y{s}*{CS}!F{s}/1000000,"")',USDM,green=True)
    frm(ws,f"N{r}",f'=IF(AND(ISNUMBER(M{r}),M{r}>0,ISNUMBER(D{r})),D{r}/M{r},"")','0.0"x";(0.0"x");"–"')
    frm(ws,f"O{r}",f'=IF(AND(ISNUMBER(H{r}),ISNUMBER({CS}!G{s}),{CS}!G{s}>0),H{r}/({CS}!G{s}*4/1000000),"")','0.0"x";(0.0"x");"–"',green=True)
    c=ws[f"P{r}"]; c.value=L["filing_url"]; c.font=Font(name=F,size=9,color="0070C0",underline="single"); c.border=B; c.alignment=Alignment(wrap_text=True); c.hyperlink=L["filing_url"]
    tx(ws,f"Q{r}","; ".join(f"{x[0][:45]} {x[1]:,.1f}" for x in L["debt_instruments"] if isnum(x[1]) and x[1]>0 and not str(x[0]).startswith("[") and not str(x[0]).upper().startswith("MEMO")),wrap=True); ws.row_dimensions[r].height=40
tx(ws,f"A{6+len(TICKERS)}",f"'Quarters of L1 covered by cash' = unrestricted cash ÷ ({LQ} L1 × {LQ} BTC): a liquidity yardstick, not a forecast (ignores HPC revenue, capex, debt service and BTC sales). HUT consolidates ABTC. "+LIQ_SOURCE_NOTE,italic=True,wrap=True,color="595959"); ws.merge_cells(f"A{6+len(TICKERS)}:Q{6+len(TICKERS)}"); ws.row_dimensions[6+len(TICKERS)].height=30

# ===== Operational_layer =====
ws=wb.create_sheet("Operational_layer"); ws.sheet_view.showGridLines=False
tx(ws,"A1",f"Operational layer — {LATEST_LABEL} (definitions verbatim; no cross-company harmonization)",bold=True,size=13,color=NAVY)
oh=["Company","Ticker","Avg operating hashrate (EH/s)","Definition (avg)","End-of-period hashrate (EH/s)","Definition (end)","Power (MW)","Definition (MW)","Fleet efficiency (J/TH)","$/kWh","$/kWh definition","MWh consumed","BTC holdings (end)","Direct NET cost / PH / day, $ (derived; avg hashrate only)","Implied kWh per BTC (energy$ ÷ $/kWh ÷ BTC)"]
for i,h in enumerate(oh):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([18,6,10,38,10,38,8,28,8,8,34,10,10,13,12]): ws.column_dimensions[get_column_letter(i+1)].width=w
ws.row_dimensions[3].height=50
for i,t in enumerate(TICKERS):
    r=4+i; per=LATEST; s=ROW[t]
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t)
    frm(ws,f"C{r}","="+PULL(t,per,"hashrate_avg"),DEC,green=True); tx(ws,f"D{r}",gx(t,per,"hashrate_avg_operating_ehs","definition")[:200],wrap=True)
    frm(ws,f"E{r}","="+PULL(t,per,"hashrate_end"),DEC,green=True); tx(ws,f"F{r}",gx(t,per,"hashrate_end_deployed_ehs","definition")[:200],wrap=True)
    frm(ws,f"G{r}","="+PULL(t,per,"power_mw"),INT,green=True); tx(ws,f"H{r}",gx(t,per,"power_mw_operating","definition")[:160],wrap=True)
    frm(ws,f"I{r}","="+PULL(t,per,"jth"),DEC,green=True); frm(ws,f"J{r}","="+PULL(t,per,"kwh"),DEC3,green=True); tx(ws,f"K{r}",gx(t,per,"power_cost_per_kwh","definition")[:200],wrap=True)
    frm(ws,f"L{r}","="+PULL(t,per,"mwh"),INT,green=True); frm(ws,f"M{r}","="+PULL(t,per,"btc_holdings"),INT,green=True)
    frm(ws,f"N{r}",f'=IF(AND(ISNUMBER(C{r}),C{r}>0,ISNUMBER({CS}!O{s})),{CS}!O{s}/(C{r}*1000*Standard!$C$6),"")','"$"#,##0.0;("$"#,##0.0);"–"')
    frm(ws,f"O{r}",f'=IF(AND(ISNUMBER({CS}!J{s}),ISNUMBER(J{r}),J{r}>0,ISNUMBER({CS}!K{s}),{CS}!K{s}>0),{CS}!J{s}/J{r}/{CS}!K{s},"")',INT)
    ws.row_dimensions[r].height=46
tx(ws,f"A{5+len(TICKERS)}","$/PH/day only where a quarterly average operating hashrate is disclosed (RIOT, BTDR; CLSK is a final-month average → indicative). Implied kWh/BTC is a consistency check between the energy line and the disclosed power price (gross vs net-of-credit definitions differ — RIOT's 3.6¢ is net of curtailment credits).",italic=True,wrap=True,color="595959"); ws.merge_cells(f"A{5+len(TICKERS)}:O{5+len(TICKERS)}"); ws.row_dimensions[5+len(TICKERS)].height=30

# ===== Checks =====
ws=wb.create_sheet("Checks"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Checks — ERROR blocks release; WARN goes to the release note; INFO documented",bold=True,size=13,color=NAVY)
ch=["Check","Company","Period","Derived (workbook)","Reported / expected","Δ","Tolerance","Result","Severity if failed","Comment"]
for i,h in enumerate(ch):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([34,16,9,14,14,12,10,8,9,70]): ws.column_dimensions[get_column_letter(i+1)].width=w
checks=[]
def addchk(name,t,per,d,rep,tol,sev,cmt): checks.append((name,t,per,d,rep,tol,sev,cmt))
for per in PERIODS:
    cs=f"Cost_stack_{per}"
    for t in TICKERS:
        p=N[t]["periods"].get(per)
        if not p: continue
        s=ROW[t]
        if isnum(g(t,per,"reported_cost_to_mine_ex_da_per_btc")):
            addchk("L0 Direct NET/BTC vs reported cost-to-mine ex-D&A",t,per,f"={cs}!Q{s}",f"={cs}!AS{s}",500,"WARN","Scope differences (CLSK energy+utilities on gross BTC; WULF net of DR) explain residuals.")
        if isnum(g(t,per,"reported_cost_to_mine_incl_da_per_btc")):
            addchk("L0 + D&A/BTC vs reported incl-D&A",t,per,f"={cs}!Q{s}+{cs}!AH{s}",f"={cs}!AU{s}",500,"WARN","DER-method rows reconcile by construction; SEG rows test the miner-depreciation attribution.")
        rp=g(t,per,"avg_btc_price_realized_or_production_value"); rpd=gx(t,per,"avg_btc_price_realized_or_production_value","definition").lower()
        if isnum(rp) and not ("implied" in rpd or "not a reported" in rpd):
            addchk("Realized price (rev ÷ BTC) vs reported avg price",t,per,f"={cs}!AM{s}",f"={cs}!AN{s}",1500,"WARN","Recognition-price vs revenue/BTC; gross vs net BTC counts; denominator adjustments (MARA ex-ADGM).")
        c_=comp(t,per); dc=g(t,per,"direct_cost_btc_gross")
        if c_ and isnum(dc):
            skip=("depreciation_excluded","total_lease","unallocated","DR_proceeds","energy_net","co_mining")
            vals=[v for k,v in c_.items() if isnum(v) and not k.startswith(skip)]
            if t=="WULF": vals=[c_.get("energy_net_of_DR",0)+c_.get("DR_proceeds_added_back",0)]
            if t=="ABTC": vals=[c_.get("operating_lease_cost_fixed_colocation_fee",0)+c_.get("variable_lease_cost_passthrough_power_and_site_costs",0)+c_.get("other_non_lease_cost_of_revenue_residual",0)+c_.get("lease_cost_recognised_outside_cost_of_revenue",0)]
            if t=="CANG": vals=[c_.get("energy_and_hosting_implied_from_reported_cost_per_btc",0)+c_.get("energy_and_hosting_implied_from_reported_cash_cost_per_btc",0)+c_.get("non_mining_and_other_cost_of_revenue_residual",0)]
            if t=="BTDR": vals=[c_.get("self_mining_electricity",0)+c_.get("self_mining_other_costs",0)]
            if t=="CLSK": vals=[c_.get("energy_owned_facilities",0)+c_.get("other_direct_non_energy_utilities",0)+c_.get("unallocated_rounding",0)]
            if t=="CORZ": vals=[c_.get("power_fees",0)+c_.get("employee_compensation",0)+c_.get("facility_operations_expense",0)+c_.get("other_segment_items",0)]
            if t=="KEEL": vals=[c_.get("energy_expenses_net_of_RECs_WTCs",0)+c_.get("infrastructure_expenses",0)+c_.get("electrical_components_and_salaries",0)+c_.get("hosting_expenses",0)]
            if vals: addchk("Direct-cost components sum to line (as extracted)",t,per,sum(vals),dc,max(150000,0.002*abs(dc)),"ERROR","Python-side arithmetic on extracted components; DIRECT_COST_OVERRIDE (BTDR) tested separately below.")
        # confidence mismatches
        for f in ["btc_mined","btc_mining_revenue","total_revenue","direct_cost_btc_gross","da_consolidated","sga_reported","sbc_in_sga","interest_expense_pnl","cash_interest_paid_3m","hashrate_avg_operating_ehs","hashrate_end_deployed_ehs","power_mw_operating","fleet_efficiency_jth","power_cost_per_kwh","reported_cost_to_mine_ex_da_per_btc","reported_cost_to_mine_incl_da_per_btc","reported_energy_cost_per_btc","curtailment_dr_credits"]:
            x=p.get(f)
            if isinstance(x,dict) and x.get("confidence")=="MISMATCH":
                addchk(f"Blind re-extraction mismatch: {f}",t,per,x.get("value"),x.get("verify_value"),max(1.0,0.005*abs(x.get("value") or 0)),"WARN",("2nd pass quote: "+(x.get("verify_quote") or ""))[:300])
# BTDR override test
for per in PERIODS:
    if ("BTDR",per) in DIRECT_COST_OVERRIDE:
        c_=comp("BTDR",per); v=sum(c_.get(k,0) for k in ("self_mining_electricity","self_mining_other_costs","co_mining_electricity","co_mining_other_costs"))
        addchk("BTDR direct cost incl. co-mining = sum of components","BTDR",per,v,DIRECT_COST_OVERRIDE[("BTDR",per)][0],150000,"ERROR","Numerator aligned with BTC denominator (incl. co-mining).")
# cash interest YTD (calendar filers): sum of the year's quarters = YTD in the latest filing of that year
for t in TICKERS:
    if str(N[t].get("fye"))!="1231": continue
    for yr in sorted({p.split("_")[1] for p in PERIODS}):
        qs=[f"Q{i}_{yr}" for i in (1,2,3,4) if f"Q{i}_{yr}" in PERIODS and f"Q{i}_{yr}"!=f"Q4_{yr}"]
        if len(qs)<2: continue
        last=qs[-1]; pl=N[t]["periods"].get(last)
        if not pl: continue
        y=pl["cash_interest_paid_ytd"]["value"]; vals=[(N[t]["periods"].get(q) or {}).get("cash_interest_paid_3m",{}).get("value") for q in qs]
        if isnum(y) and all(isnum(x) for x in vals): addchk(f"Cash interest: {' + '.join(q.split('_')[0] for q in qs)} = {3*len(qs)}M YTD",t,last,sum(vals),y,1000,"WARN",(pl["cash_interest_paid_3m"].get("note") or "")[:200])
        elif t=="RIOT" and last=="Q2_2026": addchk("Cash interest: Q1 + Q2 = 6M YTD",t,"Q2_2026",7008000,3616000,1000,"WARN","Label changed: Q1 'Cash paid for interest' 7,008k vs 6M 'net of amounts capitalized' 3,616k — Q2 3M not derivable; reference column only.")
# segment revenues sum to total (latest period, where a segment split is extracted)
for t in TICKERS:
    p=N[t]["periods"].get(LATEST)
    if not p: continue
    seg=g(t,LATEST,"revenue_by_segment"); tot=g(t,LATEST,"total_revenue")
    if isinstance(seg,dict) and isnum(tot):
        vals=[x for x in seg.values() if isnum(x)]
        if vals and len(vals)>1: addchk(f"Segment revenues sum to total ({LATEST_LABEL})",t,LATEST,sum(vals),tot,max(1000,0.01*abs(tot)),"WARN","Intersegment eliminations / rounding may explain small residuals (see Data note).")
addchk("Segment revenues sum to total (RIOT)","RIOT","Q2_2026",113736000+23213000+37286000,174235000,1000,"ERROR","Engineering net of $8,884k intersegment.")
addchk("Segment revenues sum to total (CORZ)","CORZ","Q2_2026",21535000+136670000+6000000,164200000,100000,"ERROR","Self-mining + colocation + hosted mining.")
for i,(name,t,per,d,rep,tol,sev,cmt) in enumerate(checks):
    r=4+i
    tx(ws,f"A{r}",name); tx(ws,f"B{r}",N[t]["entity"] if t in N else t); tx(ws,f"C{r}",per)
    if isinstance(d,str): frm(ws,f"D{r}",d,USD,green=True)
    else: num(ws,f"D{r}",d,USD if abs(d or 0)>=100 else DEC3)
    if isinstance(rep,str): frm(ws,f"E{r}",rep,USD,green=True)
    else: num(ws,f"E{r}",rep,USD if abs(rep or 0)>=100 else DEC3)
    frm(ws,f"F{r}",f'=IF(AND(ISNUMBER(D{r}),ISNUMBER(E{r})),D{r}-E{r},"n/a")',USD); num(ws,f"G{r}",tol,USD if tol>=100 else DEC3,color="000000")
    frm(ws,f"H{r}",f'=IF(ISNUMBER(F{r}),IF(ABS(F{r})<=G{r},"PASS",IF(I{r}="ERROR","ERROR","WARN")),"n/a")','@'); tx(ws,f"I{r}",sev,align="center"); tx(ws,f"J{r}",cmt,wrap=True); ws.row_dimensions[r].height=28
CHK_LAST=3+len(checks)
tx(ws,f"A{CHK_LAST+2}","Summary",bold=True,color=NAVY)
tx(ws,f"A{CHK_LAST+3}","PASS"); frm(ws,f"D{CHK_LAST+3}",f'=COUNTIF(H4:H{CHK_LAST},"PASS")','0')
tx(ws,f"A{CHK_LAST+4}","WARN"); frm(ws,f"D{CHK_LAST+4}",f'=COUNTIF(H4:H{CHK_LAST},"WARN")','0')
tx(ws,f"A{CHK_LAST+5}","ERROR"); frm(ws,f"D{CHK_LAST+5}",f'=COUNTIF(H4:H{CHK_LAST},"ERROR")','0')
tx(ws,f"A{CHK_LAST+6}","Verdict (checks only)"); frm(ws,f"D{CHK_LAST+6}",f'=IF(D{CHK_LAST+5}=0,"READY","BLOCKED")','@',bold=True)
tx(ws,f"A{CHK_LAST+7}","WARN rows are definitional or disclosure-driven and are listed in the Public Summary release note; ERROR rows indicate an extraction/arithmetic defect and block publication.",italic=True,color="595959"); ws.merge_cells(f"A{CHK_LAST+7}:J{CHK_LAST+7}")
CHK_SUMMARY_ROW=CHK_LAST+3

# ===== Quality_scorecard =====
ws=wb.create_sheet("Quality_scorecard"); ws.sheet_view.showGridLines=False
tx(ws,"A1",f"Quality scorecard — disclosure completeness, input confidence, comparability ({LATEST_LABEL})",bold=True,size=13,color=NAVY)
qh=["Company","Ticker","Tier","Core inputs disclosed (of 10)","Completeness","Inputs XBRL-tagged","Inputs TEXT-2x","Inputs TEXT-1x","MISMATCH","Scope","D&A method","BTC revenue share","Allocation sensitivity (L1 band width / L1)","Reported cost-to-mine?","Comparability grade","Rationale"]
for i,h in enumerate(qh):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([18,6,5,10,10,9,9,9,9,7,8,9,12,10,10,70]): ws.column_dimensions[get_column_letter(i+1)].width=w
ws.row_dimensions[3].height=55
GRADE={"RIOT":("A","Full segment disclosure, company-reported ex-/incl-D&A cost-to-mine, curtailment separate, cash interest disclosed (definition changed in Q2)."),
 "MARA":("B","Single segment; hosting mixes cost bases (owned vs hosted BTC); only energy/BTC and $/PH/day reported; large non-recurring G&A; accelerated D&A."),
 "CLSK":("B","Pure-play with miners-only D&A and cost table, but direct-cost scope = energy only (site labor outside), limiting L0 comparability."),
 "HIVE":("B","Clean cash SG&A (SBC separate), electricity split; no per-BTC cost metric; hashrate/MW tables dated a month after quarter end; D&A by revenue share."),
 "IREN":("C","Q4 derived 12M−9M; mining decommissioning distorts run-rate; SG&A includes site items; AI Cloud D&A dominates → REV D&A unreliable."),
 "CIFR":("B-","Single segment and clean direct cost, but no operational KPIs and financing layer dominated by HPC debt."),
 "CORZ":("B","Segment D&A disclosed (SEG); self-mining minority; no mining KPIs; BTC mined derived from 6M."),
 "WULF":("C+","Electricity-only scope netted of DR (grossed here); tiny volume → per-BTC metrics volatile; SG&A dominated by SBC/charity; accelerated D&A."),
 "BTDR":("C","6-K only; SBC split undisclosed for 3M; co-mining mixed into production (cost aligned); cash interest 3M not derivable."),
 "CANG":("C (T2)","6-K/20-F; hosted all-in fees embed host margin; direct cost derived from the company's cash cost per BTC (FY identity with the 20-F energy & hosting line); SEG D&A; USD reporting."),"FUFU":("n/a (T3)","6-K/20-F; cost of revenues split by counterparty (Bitmain / third parties / D&A), not by stream — self-mining cost not separable; FY2025 20-F cost-to-mine ex-D&A $77,573 is company-reported only."),
 "ABTC":("B (T2)","Clean pure-play disclosure, but cost base is a related-party hosting fee embedding Hut 8's targeted yield."),
 "BTBT":("D (T2)","Immaterial mining; winding down."),"KEEL":("n/a (T3)","Mining cost not separable; EH/s no longer disclosed."),"HUT":("n/a (T3)","ASIC cost not disclosed; economics via ABTC.")}
core=["btc_mined","btc_mining_revenue","total_revenue","direct_cost_gross","da_consolidated","sga_reported","sbc_in_sga","interest_expense_pnl","hashrate_end","power_mw"]
for i,t in enumerate(TICKERS):
    r=4+i; s=ROW[t]; per=LATEST
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t); num(ws,f"C{r}",TIER[t],'0',color="000000")
    frm(ws,f"D{r}","="+"+".join(f'IF(ISNUMBER({PULL(t,per,m)}),1,0)' for m in core),'0'); frm(ws,f"E{r}",f"=D{r}/10",PCT)
    for j,flag in enumerate(["XBRL","TEXT-2x","TEXT-1x","MISMATCH"]):
        frm(ws,f"{get_column_letter(6+j)}{r}",f'=COUNTIFS(Data!$B$4:$B${RAW_LAST},"{t}",Data!$C$4:$C${RAW_LAST},"{per}",Data!$H$4:$H${RAW_LAST},"{flag}")','0')
    frm(ws,f"J{r}",f"={CS}!D{s}",'@',green=True); frm(ws,f"K{r}",f"={CS}!AG{s}",'@',green=True); frm(ws,f"L{r}",f"={CS}!I{s}",PCT,green=True)
    frm(ws,f"M{r}",f'=IF(AND(ISNUMBER({CS}!AB{s}),ISNUMBER({CS}!Z{s}),ISNUMBER({CS}!Y{s}),{CS}!Y{s}>0),({CS}!AB{s}-{CS}!Z{s})/{CS}!Y{s},"")',PCT)
    frm(ws,f"N{r}",f'=IF(OR(ISNUMBER({CS}!AS{s}),ISNUMBER({PULL(t,per,"rep_energy_per_btc")})),"Yes","No")','@')
    tx(ws,f"O{r}",GRADE.get(t,("n/a",""))[0],bold=True,align="center"); tx(ws,f"P{r}",GRADE.get(t,("",""))[1],wrap=True); ws.row_dimensions[r].height=40
ws.conditional_formatting.add(f"E4:E{3+len(TICKERS)}",ColorScaleRule(start_type='num',start_value=0.4,start_color='F8696B',mid_type='num',mid_value=0.7,mid_color='FFEB84',end_type='num',end_value=1,end_color='63BE7B'))
tx(ws,f"A{5+len(TICKERS)}","Allocation sensitivity = (L1 at 100% allocation − L1 at 0%) ÷ L1 rev-share: the share of the headline metric that depends on the overhead allocation key (0% for a company with no SG&A would be fully determined by direct cost).",italic=True,wrap=True,color="595959"); ws.merge_cells(f"A{5+len(TICKERS)}:P{5+len(TICKERS)}")

# ===== Sources =====
ws=wb.create_sheet("Sources"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Sources — filing lineage per company × period, plus liquidity-layer sources",bold=True,size=13,color=NAVY)
sh=["Company","Ticker","Period","Form","Fiscal label","Basis","Accession","Filing date","Primary document URL","Local XBRL snapshot","Local text snapshot","Extraction caveats"]
for i,h in enumerate(sh):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([18,6,9,7,16,9,22,11,60,30,34,90]): ws.column_dimensions[get_column_letter(i+1)].width=w
r=4
for t in TICKERS:
    for per in PERIODS:
        p=N[t]["periods"].get(per)
        if not p: continue
        tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t); tx(ws,f"C{r}",per); tx(ws,f"D{r}",p.get("form") or ""); tx(ws,f"E{r}",p.get("fiscal_label") or ""); tx(ws,f"F{r}",p.get("basis") or "US GAAP")
        tx(ws,f"G{r}",p.get("accession") or ""); tx(ws,f"H{r}",p.get("filing_date") or "")
        c=ws[f"I{r}"]; c.value=p.get("url") or ""; c.font=Font(name=F,size=9,color="0070C0",underline="single"); c.border=B; c.alignment=Alignment(wrap_text=True)
        if p.get("url"): c.hyperlink=p.get("url")
        pe=PEND[per]
        xi=[os.path.basename(x) for x in glob.glob(f"{SP}/secdata/xbrl/{t}_{pe}_*.json")]; tf=[os.path.basename(x) for x in glob.glob(f"{SP}/secdata/text/{t}_{pe}_*.txt")]
        tx(ws,f"J{r}","; ".join(xi) or "(6-K: no XBRL)",wrap=True); tx(ws,f"K{r}","; ".join(tf) or "(see secdata/text/*_6K_*)",wrap=True)
        cav=p.get("caveats") or []; tx(ws,f"L{r}"," • ".join(cav)[:1500],wrap=True); ws.row_dimensions[r].height=max(30,min(110,14*len(cav)+14)); r+=1
    en=N[t].get("extraction_notes") or []
    if en:
        tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t)); tx(ws,f"B{r}",t); tx(ws,f"C{r}","notes"); tx(ws,f"L{r}"," • ".join(en)[:1500],wrap=True); ws.row_dimensions[r].height=min(110,14*len(en)+14); r+=1
r+=1; tx(ws,f"A{r}","Liquidity layer sources",bold=True,color=NAVY); r+=1
for t in TICKERS:
    L=LIQ.get(t)
    if not L: continue
    for sid,sv in L["sources"].items():
        tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t)); tx(ws,f"B{r}",t); tx(ws,f"C{r}",sid); tx(ws,f"D{r}",sv.get("date") or ""); tx(ws,f"E{r}",sv.get("title") or "",wrap=True); ws.merge_cells(f"E{r}:H{r}")
        c=ws[f"I{r}"]; c.value=sv.get("url") or ""; c.font=Font(name=F,size=9,color="0070C0",underline="single"); c.border=B
        if sv.get("url"): c.hyperlink=sv.get("url")
        r+=1
r+=1; tx(ws,f"A{r}","BTC spot (liquidity layer only)"); tx(ws,f"E{r}",BTC_SPOT[1]); ws.merge_cells(f"E{r}:H{r}"); c=ws[f"I{r}"]; c.value=BTC_SPOT[3] if len(BTC_SPOT)>3 else "https://www.coingecko.com/en/coins/bitcoin"; c.hyperlink=c.value; c.font=Font(name=F,size=9,color="0070C0",underline="single")

# ===== Glossary / AI_HPC / Excluded / Reproducibility / Change_log / Version_Log / Public_Summary =====
ws=wb.create_sheet("Glossary"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Glossary",bold=True,size=13,color=NAVY); ws.column_dimensions["A"].width=32; ws.column_dimensions["B"].width=110
gl=[("BTC mined (denominator)","Bitcoin produced by self-mining (incl. co-mining/hosted production where the company books the related costs); MARA excludes the ADGM equity-method share; net of pool fees where reported net."),
("BTC mining revenue","Segment revenue from bitcoin mining as tagged in XBRL or stated in MD&A; ASC 606 net of pool-operator fees."),
("Revenue share","BTC mining revenue ÷ total consolidated revenue (capped at 100%); primary allocation key."),
("L0-E Energy / BTC","Electricity/power component of BTC-mining cost of revenue, gross of credits, ÷ BTC (owned-site BTC where applicable)."),
("L0 Direct NET / BTC","Segment cost of revenue excl. D&A (gross) − disclosed credits, ÷ BTC. Scope code says what the line contains."),
("Cash SG&A run-rate","Reported SG&A/G&A − SBC booked in SG&A − other disclosed non-cash − disclosed non-recurring cash items."),
("L1 CASH OPERATING COST / BTC","L0 + allocated cash SG&A ÷ BTC. Primary metric; band shows 0% / cost-share / rev-share / 100% allocation."),
("Cost-share key","BTC-mining segment cost of revenue ÷ total cost of revenue — alternative allocation key."),
("L2 CASH BUSINESS COST / BTC","L1 + allocated P&L interest expense ÷ BTC."),
("L3 FULL ACCOUNTING COST / BTC","L2 + D&A attributable ÷ BTC. Run-rate variant removes disclosed accelerated depreciation."),
("D&A method","SEG segment/miner-class disclosed • DER derived from reported per-BTC metrics • REV revenue share of consolidated • NA."),
("Realized price / BTC","BTC mining revenue ÷ BTC mined (recognition-price-weighted average of mined BTC)."),
("Reported cost-to-mine","Company-defined MD&A metric; definitions differ (RIOT: direct ex-D&A net of curtailment incl. site opex; CLSK: energy & utilities; WULF: electricity net of DR)."),
("Tier","1 owner-operator with computable stack • 2 hosted cost base • 3 mining cost not separable/disclosed."),
("Headline set","Tier 1 companies with BTC mined ≥ Standard!C4 in the quarter; others in appendix."),
("Confidence","XBRL tagged fact • TEXT-2x text figure confirmed by blind second pass • TEXT-1x single extraction • MISMATCH passes disagree (Checks)."),
("TTM","Trailing four quarters, production-weighted (Σ$ ÷ ΣBTC).")]
for i,(a,b) in enumerate(gl):
    r=3+i; tx(ws,f"A{r}",a,bold=True,fill=SUB_FILL,wrap=True); tx(ws,f"B{r}",b,wrap=True); ws.row_dimensions[r].height=max(30,15*(len(b)//110+1))

ws=wb.create_sheet("AI_HPC_segments"); ws.sheet_view.showGridLines=False
tx(ws,"A1",f"Non-BTC business context — {LATEST_LABEL} (from filings)",bold=True,size=13,color=NAVY)
for i,h in enumerate(["Company","Ticker",f"BTC revenue share {LQ}",f"Non-BTC revenue {LQ}, $","Context (from extraction)"]):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([18,6,11,14,120]): ws.column_dimensions[get_column_letter(i+1)].width=w
for i,t in enumerate(TICKERS):
    r=4+i; s=ROW[t]
    tx(ws,f"A{r}",SHORT_NAME.get(t,N[t]["entity"] or t),bold=True); tx(ws,f"B{r}",t); frm(ws,f"C{r}",f"={CS}!I{s}",PCT,green=True); frm(ws,f"D{r}",f'=IF(AND(ISNUMBER({CS}!H{s}),ISNUMBER({CS}!G{s})),{CS}!H{s}-{CS}!G{s},"")',USD)
    ctx=N[t].get("ai_hpc_context"); tx(ws,f"E{r}",(json.dumps(ctx,ensure_ascii=False) if isinstance(ctx,dict) else str(ctx or ""))[:1200],wrap=True); ws.row_dimensions[r].height=55

ws=wb.create_sheet("Excluded_data"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Items deliberately excluded from the cost layers",bold=True,size=13,color=NAVY)
for i,h in enumerate(["Item","Treatment","Examples (from filings, Q2 2026 unless stated)"]):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
for i,w in enumerate([34,40,90]): ws.column_dimensions[get_column_letter(i+1)].width=w
ex=[("Fair-value changes on digital assets","Excluded (mark-to-market)","RIOT −$74.6m; HUT −$138.6m; ABTC −$71.2m; CLSK −$16.5m"),
("Fair-value changes on warrants/derivatives","Excluded","WULF Google warrants −$755.7m; ABTC/HUT Bitmain put options +$18.3m; BTDR Norway PPA +$13.0m"),
("Impairments / held-for-sale remeasurement","Excluded (non-cash, non-recurring)","IREN $450.4m (+$102.1m HFS); RIOT $28.0m; CORZ $19.5m HFS; BTBT $46.0m LsETH"),
("Accelerated depreciation","Kept in L3 (strict); removed in the run-rate variant; disclosed separately","MARA $28.1m; KEEL $63.0m; WULF $2.6m"),
("Stock-based compensation","Excluded from cash SG&A where booked there","WULF $83.9m (+$14.4m stock charity); HUT $51.2m; MARA $45.2m; IREN $42.9m"),
("Non-recurring cash in SG&A","Excluded from run-rate cash SG&A","MARA M&A $15.4m + litigation $10.2m; CLSK $5.9m (financing/BD fees, litigation, severance); CORZ $0.4m"),
("Restructuring / disposal / debt extinguishment","Excluded","MARA restructuring $1.8m; BTDR disposal loss $17.2m; WULF extinguishment $7.1m; CORZ Block/Proto termination $41.9m"),
("Regulatory provisions","Excluded (non-operating)","HIVE Swedish VAT provision $84.7m (SEK 822m)"),
("Colocation / HPC start-up costs","Excluded (non-BTC segment)","CORZ $27.0m colocation organizational & site startup; IREN AI Cloud cost of revenue"),
("Not derivable quarters","Left blank (no estimate); TTM blank for the company","CORZ Q4 2025 direct cost (10-K carved startup costs out of segment cost of revenue without restating 9M → FY−9M labor negative); FUFU all quarters (not separable)"),
("Capitalized interest","Excluded (balance-sheet, HPC construction)","CIFR $16.5m; WULF $32.7m; CORZ $11.7m; RIOT $3.4m; HUT $5.7m"),
("Interest income","Not netted against interest expense","Cap rule: allocated interest ≥ 0"),
("External estimates","Excluded entirely from cost layers","No analyst/model data; BTC spot used only on the Liquidity sheet and labelled")]
for i,(a,b,c_) in enumerate(ex):
    r=4+i; tx(ws,f"A{r}",a,bold=True,wrap=True); tx(ws,f"B{r}",b,wrap=True); tx(ws,f"C{r}",c_,wrap=True); ws.row_dimensions[r].height=30

ws=wb.create_sheet("Reproducibility"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Reproducibility — pipeline, scripts, data snapshot",bold=True,size=13,color=NAVY); ws.column_dimensions["A"].width=30; ws.column_dimensions["B"].width=120
sha=hashlib.sha256(open(NORM,"rb").read()).hexdigest()
rep=[("Snapshot date (UTC)",datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M")+" — EDGAR state as downloaded"),
("Step 1 — locate filings","scripts/find_filings.py / find_filings2.py: data.sec.gov/submissions → forms and accessions for the report dates → filings_index*.json"),
("Step 2 — XBRL facts","scripts/fetch_xbrl_instances.py / fetch_generic.py: EDGAR directory index → *_htm.xml instance → parsed contexts (periods, explicit/typed dimensions), units, facts → secdata/xbrl/{T}_{period}_{form}.json. Companyfacts API not used (drops dimensional facts and extensions)."),
("Step 3 — filing text","scripts/fetch_text.py / fetch_generic.py / fetch_6k.py: primary HTML and 6-K exhibits → tag-stripped text → secdata/text/*.txt; MD&A KPIs located with regex (scripts/tq.py, xq.py)."),
("Step 4 — extraction","EXTRACTION_SPEC.md (+ EXTRACTION_SPEC_2025.md): schema and rules (every value needs an XBRL concept or verbatim quote; no estimates; verbatim definitions). Parallel runs → extract/{T}.json, extract_2025/{T}.json. Blind second pass → verify/verify_results.json (values hidden from the verifier)."),
("Step 5 — normalization","scripts/normalize_v2.py → normalized.json (ticker×period×metric with source/definition/derivation/confidence). SHA-256: "+sha),
("Step 6 — overlay","scripts/overlay_std.py: tiers, scope codes, denominator/numerator alignment (MARA ex-ADGM; BTDR co-mining), D&A attribution, non-recurring/non-cash SG&A items, accelerated D&A, parameters — each with a filing citation."),
("Step 7 — workbook","scripts/build_std.py: Data keyed table → Cost_stack_<period> via INDEX/MATCH → all derived metrics are formulas → TTM/Ranking/Energy/Time_series/Liquidity/Checks/Scorecard/Public_Summary reference Cost_stack. One raw input changed → everything recomputes."),
("Step 8 — validation","scripts/validate_cost_model.py: LibreOffice headless recalc (zero formula errors) → scripts/mining_cost_engine.py independent recomputation of every derived cell (tolerance $1/BTC) → Checks scan (ERROR blocks) → fingerprint → Version_Log stamp → verdict."),
("Re-run","python3 -I scripts/normalize_v2.py; python3 -I scripts/build_std.py; python3 -I scripts/validate_cost_model.py <xlsx> --recalc"),
("Bundle","Mining_Cost_Standard_v1.0_repro.zip: README, EXTRACTION_SPEC*.md, scripts/, extract*/ , verify/, normalized.json, nav/liquidity_cohort.json, filings_index*.json (XBRL/text snapshots regenerated by steps 2–3)."),
("Determinism caveat","XBRL-tagged inputs are deterministic. MD&A text metrics were read by an LLM against the spec and re-read blind by a second run; confidence flags record agreement. Every Data row carries the exact source, so any value is re-verifiable in minutes.")]
for i,(a,b) in enumerate(rep):
    r=3+i; tx(ws,f"A{r}",a,bold=True,fill=SUB_FILL,wrap=True); tx(ws,f"B{r}",b,wrap=True); ws.row_dimensions[r].height=max(30,15*(len(b)//115+1))

ws=wb.create_sheet("Change_log"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Change log",bold=True,size=13,color=NAVY); ws.column_dimensions["A"].width=8; ws.column_dimensions["B"].width=12; ws.column_dimensions["C"].width=130
for i,h in enumerate(["Version","Date","Changes"]):
    c=ws.cell(row=3,column=i+1,value=h); hdr(c)
cl=[("DB v1.0","Apr 2026","Initial report-only database; mixed Q4 2025/FY2025 periods; revenue-share SG&A; P&L interest."),
("DB v2.0","19 May 2026","Q1 2026 harmonization; cash interest; operational layer; alt SG&A; cost stacks; 3 fully computable companies."),
("DB v3.0","12 Oct 2026","Q2 2026 primary + Q1 2026 on one XBRL pipeline; 13 companies; 9 Tier-1 stacks; scope codes; gross credits; cash SG&A run-rate; L1 primary; D&A hierarchy; keyed Data + INDEX/MATCH; Validation, Scorecard, Reproducibility; independent Python recompute."),
("Standard v1.0 · 2026Q3",datetime.date.today().isoformat(),"Data cut rolled to Q3 2026 (10-Q/6-K filed 2–12 Nov 2026) on the same rules — standard number unchanged. Companies without a Q3 filing at the cut are PENDING (no estimate). TTM window = Q4 2025–Q3 2026; Q3 2025 kept in Time_series/Energy_layer. Liquidity layer now from the same Q3 balance sheets (cash, restricted cash, BTC held, debt principal by instrument, equity); BTC spot = the site's daily close feed (same figure as the Capacity base). Blind second pass on Q3 2026 text inputs; prior periods keep their published confidence flags and values (base_inputs.json = v1.0 2026Q2 inputs, SHA-256 7922aeb6…)."),
("Standard v1.0","2026-10-17","Renamed Mining Cost Standard. Added: L0-E energy layer; L1 allocation band (0 / cost-share / rev-share / 100); run-rate D&A ex-accelerated; materiality threshold; production-weighted cohort statistics; TTM over four quarters (Q3 2025–Q2 2026 re-extracted on the same pipeline); liquidity layer shared with the NAV standard; blind second-pass verification with confidence flags; denominator/numerator alignment (MARA ex-ADGM; BTDR co-mining); CANG/FUFU added; Public Summary, Version Log, Checks with ERROR/WARN, engine + validator.")]
for i,(a,b,c_) in enumerate(cl):
    r=4+i; tx(ws,f"A{r}",a,bold=True); tx(ws,f"B{r}",b); tx(ws,f"C{r}",c_,wrap=True); ws.row_dimensions[r].height=70 if "Standard" in a else 30

ws=wb.create_sheet("Version_Log"); ws.sheet_view.showGridLines=False
tx(ws,"A1","Version log (stamped by validate_cost_model.py)",bold=True,size=13,color=NAVY); ws.column_dimensions["A"].width=34; ws.column_dimensions["B"].width=90
vl=[("Standard version",VERSION),("Data cut (latest quarter)",CUT+" — "+CUT_NOTE),("Periods",", ".join(PERIODS)+f" (TTM = {', '.join(TTM_PERIODS)})"),("Companies",", ".join(TICKERS)+(f"; PENDING at cut: {', '.join(sorted(PENDING))}" if PENDING else "")),
("Build date (UTC)",datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M")),("Inputs fingerprint (SHA-256 normalized.json)",sha),
("LibreOffice recalc","pending"),("Engine compare","pending"),("Checks","pending"),("Blind verification","pending"),("Verdict","pending"),("Validated at (UTC)","pending")]
for i,(a,b) in enumerate(vl):
    r=3+i; tx(ws,f"A{r}",a,bold=True,fill=SUB_FILL); tx(ws,f"B{r}",b,wrap=True)
VL_ROWS={a:3+i for i,(a,b) in enumerate(vl)}

# ===== Public_Summary (EN) =====
ws=wb.create_sheet("Public_Summary",0); ws.sheet_view.showGridLines=False
ws.column_dimensions["A"].width=3
for col,w in zip("BCDEFGHIJKLM",[26,8,12,12,12,12,12,12,12,12,12,60]): ws.column_dimensions[col].width=w
tx(ws,"B2",f"Cost to Mine One Bitcoin — Public Miners, {LATEST_LABEL}",bold=True,size=16,color=NAVY); ws["B2"].border=Border()
tx(ws,"B3",f"HASHFLOPS Mining Cost Standard v{VERSION} · strict report-only, SEC XBRL-sourced · data cut {CUT} · headline metric: L1 cash operating cost per BTC (direct mining cost + allocated cash SG&A; before financing and D&A)",italic=True,color="595959",wrap=True); ws.merge_cells("B3:M3"); ws.row_dimensions[3].height=30; ws["B3"].border=Border()
# KPI block
kr=5
tx(ws,f"B{kr}",f"Cohort (headline set, {LATEST_LABEL})",bold=True,fill=SUB_FILL); ws.merge_cells(f"B{kr}:D{kr}")
kpis=[("Production-weighted L1 cash operating cost / BTC",f"=Ranking!G{RANK_STATS_ROW}",PB),("Production-weighted realized price / BTC",f"=Ranking!G{RANK_STATS_ROW+1}",PB),("Cohort cash operating margin",f"=Ranking!G{RANK_STATS_ROW+2}",PCT),("Median L1 / BTC",f"=Ranking!G{RANK_STATS_ROW+3}",PB),("Range L1 / BTC (min – max)",f'=IFERROR(TEXT(Ranking!G{RANK_STATS_ROW+4},"$#,##0")&" – "&TEXT(Ranking!H{RANK_STATS_ROW+4},"$#,##0"),"")','@'),("Headline companies / Σ BTC mined",f'=Ranking!G{RANK_STATS_ROW+5}&" companies / "&TEXT(Ranking!H{RANK_STATS_ROW+5},"#,##0")&" BTC"','@')]
for i,(a,f_,fmt) in enumerate(kpis):
    r=kr+1+i; tx(ws,f"B{r}",a); frm(ws,f"D{r}",f_,fmt,green=True,bold=True); ws.merge_cells(f"B{r}:C{r}")
# headline table
hr=kr+9
tx(ws,f"B{hr}",f"Headline table — Tier 1 owner-operators with ≥ threshold BTC mined in {LATEST_LABEL} (ranked by L1)",bold=True,color=NAVY); ws.merge_cells(f"B{hr}:M{hr}")
ph=["Company","Ticker","Scope","L0-E Energy/BTC","L0 Direct NET/BTC","L1 Cash operating/BTC","L1 band (0%–100%)","L2 Cash business/BTC","L3 Full/BTC",f"Realized price {LQ}","Cash op. margin","L1 TTM (4Q)","Comparability flag"]
for i,h in enumerate(ph):
    c=ws.cell(row=hr+1,column=2+i,value=h); hdr(c)
ws.row_dimensions[hr+1].height=42
rk_first=5; rk_last=4+len(t1)
for i,t in enumerate(t1):
    r=hr+2+i; rr=rk_first+i
    frm(ws,f"B{r}",f"=Ranking!B{rr}",'@',green=True); ws[f"B{r}"].alignment=Alignment(horizontal="left"); frm(ws,f"C{r}",f"=Ranking!C{rr}",'@',green=True); frm(ws,f"D{r}",f"=Ranking!D{rr}",'@',green=True)
    frm(ws,f"E{r}",f"=Ranking!E{rr}",PB,green=True); frm(ws,f"F{r}",f"=Ranking!F{rr}",PB,green=True); frm(ws,f"G{r}",f"=Ranking!G{rr}",PB,green=True,bold=True,fill=KEY_FILL)
    frm(ws,f"H{r}",f'=IFERROR(TEXT(Ranking!H{rr},"$#,##0")&" – "&TEXT(Ranking!J{rr},"$#,##0"),"")','@',green=True)
    frm(ws,f"I{r}",f"=Ranking!K{rr}",PB,green=True); frm(ws,f"J{r}",f"=Ranking!L{rr}",PB,green=True); frm(ws,f"K{r}",f"=Ranking!N{rr}",PB,green=True); frm(ws,f"L{r}",f"=Ranking!O{rr}",PCT,green=True)
    frm(ws,f"M{r}",f'=IFERROR(TEXT(Ranking!P{rr},"$#,##0"),"n/a")&"  |  "&Ranking!W{rr}&"  |  "&Ranking!X{rr}','@',green=True); ws[f"M{r}"].alignment=Alignment(horizontal="left",wrap_text=True); ws.row_dimensions[r].height=30
PS_TABLE_END=hr+1+len(t1)
nr=PS_TABLE_END+2
tx(ws,f"B{nr}","How to read",bold=True,color=NAVY)
reads=["L0-E energy per BTC is the most comparable layer (electricity is disclosed by almost every miner). L0 adds other direct site costs as each company books them — the scope code (E / E+S / E+S+H / H) says what is inside.",
"L1 cash operating cost is the headline: direct cost plus corporate cash overhead allocated by BTC revenue share. The band shows the same metric at 0% and 100% allocation — the wider the band, the more the number depends on the allocation key (multi-segment miners).",
"L2 adds P&L interest (capital structure); L3 adds D&A attributable to mining. Both are secondary: HPC-construction debt (CIFR, WULF, CORZ) and AI-cloud depreciation (IREN) are not mining costs even when revenue share pushes them into the stack.",
"Realized price = BTC mining revenue ÷ BTC mined, from the filings; no external price is used in the cost layers. Rows below the materiality threshold, hosted miners (Tier 2) and non-separable cases (Tier 3) are in the appendix sheets.",
"Every input is traceable: Data sheet → XBRL concept with dimensions or a verbatim MD&A quote → Sources sheet with accession and URL. Two verification layers (LibreOffice recalc; independent Python engine) and a blind second-pass re-extraction of text inputs."]
for i,s_ in enumerate(reads):
    tx(ws,f"B{nr+1+i}",s_,wrap=True); ws.merge_cells(f"B{nr+1+i}:M{nr+1+i}"); ws.row_dimensions[nr+1+i].height=30
ir=nr+7
tx(ws,f"B{ir}","Model integrity",bold=True,color=NAVY)
integ=[("Standard / data cut",f"v{VERSION} / {CUT} ({CUT_NOTE})"),("Periods covered",", ".join(PERIODS)+f"; TTM = {TTM_PERIODS[-1].replace('_',' ')}–{TTM_PERIODS[0].replace('_',' ')}"),("Inputs fingerprint (SHA-256)",sha),("LibreOffice recalc",f"=Version_Log!B{VL_ROWS['LibreOffice recalc']}"),("Engine compare",f"=Version_Log!B{VL_ROWS['Engine compare']}"),("Checks",f"=Version_Log!B{VL_ROWS['Checks']}"),("Blind verification",f"=Version_Log!B{VL_ROWS['Blind verification']}"),("Verdict",f"=Version_Log!B{VL_ROWS['Verdict']}"),("Validated at (UTC)",f"=Version_Log!B{VL_ROWS['Validated at (UTC)']}")]
for i,(a,b) in enumerate(integ):
    r=ir+1+i; tx(ws,f"B{r}",a,fill=SUB_FILL); ws.merge_cells(f"B{r}:C{r}")
    if isinstance(b,str) and b.startswith("="): frm(ws,f"D{r}",b,'@',green=True); ws[f"D{r}"].alignment=Alignment(horizontal="left")
    else: tx(ws,f"D{r}",b)
    ws.merge_cells(f"D{r}:M{r}")
dr=ir+11
tx(ws,f"B{dr}","Disclaimer",bold=True,color=NAVY)
disc=["1. Informational research; not investment advice, not an offer or solicitation; no recommendations, target prices or signals are made or implied.",
"2. All cost figures are derived from issuers' SEC filings under the published Standard; they are model outputs whose definitions (scope codes, allocation keys, D&A attribution) may differ from the issuers' own metrics and from other research providers. Per-BTC costs are sensitive to production volume and to curtailment behaviour, which is itself price-dependent.",
"3. Sources are cited per input; figures may be revised when issuers restate or when extraction errors are found (errata published with the next release; prior versions are retained).",
"4. Conflict of interest: the author may hold positions in companies covered; existence of a position is disclosed on the publication page, size is not; no trading ±2 trading days around publication.",
"5. Readers are encouraged to reproduce the results from the reproducibility package (scripts, inputs, fingerprint)."]
for i,s_ in enumerate(disc):
    tx(ws,f"B{dr+1+i}",s_,wrap=True); ws.merge_cells(f"B{dr+1+i}:M{dr+1+i}"); ws.row_dimensions[dr+1+i].height=30 if i!=1 else 44

# order
order=["Public_Summary","Version_Log","Standard","Glossary"]+[f"Cost_stack_{p}" for p in PERIODS]+["TTM","Ranking","Energy_layer","Time_series","Liquidity","Operational_layer","Checks","Quality_scorecard","Data","Sources","AI_HPC_segments","Excluded_data","Reproducibility","Change_log"]
wb._sheets=[wb[s] for s in order if s in wb.sheetnames]
wb.save(OUT)
json.dump({"out":OUT,"periods":PERIODS,"tickers":TICKERS,"row":ROW,"raw_last":RAW_LAST,"ttm_first_row":4,"ranking_t1":t1,"vl_rows":VL_ROWS,"sha":sha,"chk_summary_row":CHK_SUMMARY_ROW},open(f"{SP}/build_meta.json","w"),indent=1)
print("saved",OUT,"| periods",PERIODS,"| tickers",len(TICKERS),"| data rows",len(rows),"| checks",len(checks))
