"""Independent engine for the Mining Cost Standard: recomputes every derived cell of Cost_stack_<period>, TTM and the
Ranking cohort statistics from normalized.json + overlay_std (via cost_common.derive_rows) in pure Python and compares
them with the LibreOffice-computed values in the workbook. No Excel formulas are executed here.
Usage: mining_cost_engine.py --xlsx <workbook> [--json out.json]"""
import json, sys, os, argparse
sys.path.insert(0, os.path.dirname(__file__))
from overlay_std import *
from cost_common import derive_rows, isnum
from openpyxl import load_workbook

# 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
ap=argparse.ArgumentParser(); ap.add_argument("--xlsx",required=True); ap.add_argument("--json"); a=ap.parse_args()
N=json.load(open(NORM)); meta=json.load(open(f"{SP}/build_meta.json"))
PERIODS=meta["periods"]; TICKERS=meta["tickers"]; ROW=meta["row"]; LATEST=PERIODS[0]; TTM_PERIODS=PERIODS[:4]
rows=derive_rows(N,PERIODS,TICKERS)
D={}; T={}
for r in rows:
    D[(r["ticker"],r["period"],r["metric"])]=r["value"]; T[(r["ticker"],r["period"],r["metric"])]=r["text"]
def v(t,per,m): return D.get((t,per,m))
def tv(t,per,m): return T.get((t,per,m))

def stack(t,per):
    o={}
    tier=TIER[t]; o["C"]=tier
    F=v(t,per,"btc_mined"); G=v(t,per,"btc_mining_revenue"); H=v(t,per,"total_revenue")
    I=min(1.0,G/H) if isnum(G) and isnum(H) and H else None
    J=v(t,per,"energy_cost"); Kb=v(t,per,"energy_btc_base"); K=Kb if isnum(Kb) else F
    L=J/K if (tier<3 and isnum(J) and isnum(K) and K>0) else None
    M=v(t,per,"direct_cost_gross"); Nn=v(t,per,"curtailment_credits")
    O=(M-(Nn if isnum(Nn) else 0)) if isnum(M) else None
    P=M/F if (tier<3 and isnum(M) and isnum(F) and F>0) else None
    Q=O/F if (tier<3 and isnum(O) and isnum(F) and F>0) else None
    R=v(t,per,"sga_reported"); S=v(t,per,"sbc_in_sga"); Tn=v(t,per,"other_noncash_sga"); U=v(t,per,"nonrec_cash_sga")
    V=(R-(S or 0)-(Tn or 0)-(U or 0)) if isnum(R) else None
    W=v(t,per,"cost_share")
    X=V*I/F if (tier<3 and isnum(V) and I is not None and isnum(F) and F>0) else None
    Y=Q+X if (Q is not None and X is not None) else None
    Z=Q
    AA=Q+V*W/F if (Q is not None and isnum(V) and isnum(W) and isnum(F) and F>0) else None
    AB=Q+V/F if (Q is not None and isnum(V) and isnum(F) and F>0) else None
    AC=v(t,per,"interest_expense_pnl")
    AD=max(AC,0)*I/F if (tier<3 and isnum(AC) and I is not None and isnum(F) and F>0) else None
    AE=Y+AD if (Y is not None and AD is not None) else None
    AG=tv(t,per,"da_method")
    if AG=="REV":
        dac=v(t,per,"da_consolidated"); AF=dac*I if (isnum(dac) and I is not None) else None
    elif AG=="NA": AF=None
    else: AF=v(t,per,"da_btc_attrib")
    AH=AF/F if (AF is not None and isnum(F) and F>0) else None
    AI=AE+AH if (AE is not None and AH is not None) else None
    AJ=v(t,per,"accelerated_da"); rule=(tv(t,per,"accelerated_da") or "").strip()
    if AH is not None:
        if isnum(AJ):
            if rule=="REV": AK=(AF-AJ*I)/F
            elif rule=="True": AK=(AF-AJ)/F
            else: AK=AH
        else: AK=AH
    else: AK=None
    AL=AE+AK if (AE is not None and AK is not None) else None
    AM=G/F if (isnum(G) and isnum(F) and F>0) else None
    AO=(AM-Y)/AM if (AM and Y is not None) else None
    AP=(AM-AE)/AM if (AM and AE is not None) else None
    AQ=(AM-AI)/AM if (AM and AI is not None) else None
    AS=v(t,per,"rep_cost_ex_da_per_btc"); AT=Q-AS if (isnum(AS) and Q is not None) else None
    AU=v(t,per,"rep_cost_incl_da_per_btc"); AV=Q+AH-AU if (isnum(AU) and Q is not None and AH is not None) else None
    AW="HEADLINE" if (tier==1 and isnum(F) and F>=MATERIALITY_BTC and Y is not None) else ("appendix" if Y is not None else "n/c")
    o.update(dict(_J=J,_F=F,_G=G,I=I,K=K,L=L,O=O,P=P,Q=Q,V=V,X=X,Y=Y,Z=Z,AA=AA,AB=AB,AD=AD,AE=AE,AF=AF,AH=AH,AI=AI,AK=AK,AL=AL,AM=AM,AO=AO,AP=AP,AQ=AQ,AT=AT,AV=AV,AW=AW))
    return o

TOL={"I":1e-6,"K":0.5,"L":1,"O":1,"P":1,"Q":1,"V":1,"X":1,"Y":1,"Z":1,"AA":1,"AB":1,"AD":1,"AE":1,"AF":1,"AH":1,"AI":1,"AK":1,"AL":1,"AM":1,"AO":1e-6,"AP":1e-6,"AQ":1e-6,"AT":1,"AV":1,"C":0}
wb=load_workbook(a.xlsx,data_only=True)
n_cells=n_ok=0; bad=[]; S={}
for per in PERIODS:
    ws=wb[f"Cost_stack_{per}"]
    for t in TICKERS:
        r=ROW[t]
        if per not in N[t]["periods"]: continue
        st=stack(t,per); S[(t,per)]=st
        for col,val in st.items():
            if col.startswith('_'): continue
            wv=ws[f"{col}{r}"].value; n_cells+=1
            if col=="AW": ok=(wv==val)
            elif val is None: ok=(wv in (None,""))
            else: ok=isnum(wv) and abs(wv-val)<=TOL[col]
            if ok: n_ok+=1
            else: bad.append((per,t,col,val,wv))
# TTM
ws=wb["TTM"]; ttm={}
for i,t in enumerate(TICKERS):
    r=meta["ttm_first_row"]+i
    sts=[S.get((t,p)) for p in TTM_PERIODS]
    if all(s is not None for s in sts):
        E=sum(v(t,p,"btc_mined") or 0 for p in TTM_PERIODS); Fr=sum(v(t,p,"btc_mining_revenue") or 0 for p in TTM_PERIODS)
        okE=all(isnum(v(t,p,"btc_mined")) for p in TTM_PERIODS); okF=all(isnum(v(t,p,"btc_mining_revenue")) for p in TTM_PERIODS)
        okO=all(s["O"] is not None for s in sts); okV=all(s["V"] is not None and s["I"] is not None for s in sts); okJ=all(s["J"] if False else True for s in sts)
        Hs=sum(s["O"] for s in sts) if okO else None
        Is=sum(s["V"]*s["I"] for s in sts) if okV else None
        okAC=all(isnum(v(t,p,"interest_expense_pnl")) and s["I"] is not None for p,s in zip(TTM_PERIODS,sts))
        Js=sum(max(v(t,p,"interest_expense_pnl"),0)*s["I"] for p,s in zip(TTM_PERIODS,sts)) if okAC else None
        okK=all(s["AF"] is not None for s in sts); Ks=sum(s["AF"] for s in sts) if okK else None
        M_=Hs/E if (okE and Hs is not None and E>0 and TIER[t]<3) else None
        N_=M_+Is/E if (M_ is not None and Is is not None) else None
        O_=N_+Js/E if (N_ is not None and Js is not None) else None
        P_=O_+Ks/E if (O_ is not None and Ks is not None) else None
        Q_=Fr/E if (okE and okF and E>0) else None
        exp={"E":E if okE else None,"M":M_,"N":N_,"O":O_,"P":P_,"Q":Q_}
    else:
        exp={"E":None,"M":None,"N":None,"O":None,"P":None,"Q":None}
    for col,val in exp.items():
        wv=ws[f"{col}{r}"].value; n_cells+=1
        ok=(wv in (None,"")) if val is None else (isnum(wv) and abs(wv-val)<=1)
        if ok: n_ok+=1
        else: bad.append(("TTM",t,col,val,wv))
# Ranking cohort stats
ws=wb["Ranking"]; t1=meta["ranking_t1"]
hl=[(t,S[(t,LATEST)]) for t in t1 if (t,LATEST) in S and S[(t,LATEST)]["AW"]=="HEADLINE"]
sumB=sum(v(t,LATEST,"btc_mined") for t,_ in hl); sumC=sum(s["Y"]*v(t,LATEST,"btc_mined") for t,s in hl); sumR=sum(v(t,LATEST,"btc_mining_revenue") for t,_ in hl)
import statistics
exp_stats={"weighted_L1":sumC/sumB,"weighted_price":sumR/sumB,"margin":(sumR/sumB-sumC/sumB)/(sumR/sumB),"median":statistics.median([s["Y"] for _,s in hl]),"n":len(hl),"sumBTC":sumB}
# locate stats rows in Ranking: find label cells
lab={}
for r in range(1,ws.max_row+1):
    b=ws[f"B{r}"].value
    if isinstance(b,str):
        if b.startswith("Production-weighted L1"): lab["weighted_L1"]=ws[f"G{r}"].value
        elif b.startswith("Production-weighted realized"): lab["weighted_price"]=ws[f"G{r}"].value
        elif b.startswith("Cohort cash operating margin"): lab["margin"]=ws[f"G{r}"].value
        elif b.startswith("Median L1"): lab["median"]=ws[f"G{r}"].value
        elif b.startswith("Headline companies"): lab["n"]=ws[f"G{r}"].value; lab["sumBTC"]=ws[f"H{r}"].value
for k,val in exp_stats.items():
    wv=lab.get(k); n_cells+=1
    ok=isnum(wv) and abs(wv-val)<=(1e-6 if k=="margin" else 1)
    if ok: n_ok+=1
    else: bad.append(("Ranking","cohort",k,val,wv))
print(f"Engine compare: {n_cells} derived values, {n_ok} match, {len(bad)} mismatch")
for b in bad[:50]: print("  MISMATCH",b)
print(("Cohort (headline, "+LATEST.replace('_',' ')+"): weighted L1 ${:,.0f} | weighted price ${:,.0f} | margin {:.1%} | median ${:,.0f} | n={} | ΣBTC {:,}").format(exp_stats["weighted_L1"],exp_stats["weighted_price"],exp_stats["margin"],exp_stats["median"],exp_stats["n"],exp_stats["sumBTC"]))
if a.json:
    json.dump({"n_cells":n_cells,"n_ok":n_ok,"mismatches":bad,"cohort":exp_stats,"stacks":{f"{t}|{p}":s for (t,p),s in S.items()}},open(a.json,"w"),indent=1,default=str)
sys.exit(0 if not bad else 1)
