# -*- coding: utf-8 -*-
"""
mining_nav_engine.py — independent recomputation of the Mining NAV Standard v1.1 (transaction-based ASIC curve) for every covered company.
Reads the per-company JSON data files + the standard parameters (nav_common.py) and computes the NAV tiers
without touching any workbook formula. With --xlsx it compares against the workbook's cached values.

Usage: python3 -I mining_nav_engine.py [--xlsx Mining_NAV_Standard_v1.0.xlsx] [--json out.json] [--spot 82308.83]
"""
import sys, os, json, argparse, datetime as dt
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nav_common as C
import asic_deals as AD

ENGINE_VERSION = "1.1"


def compute(t, d, adj, P, curve):
    """curve: dict(fit=..., params=...) from asic_deals (None = unavailable) — NAV-M only when the deal curve is available."""
    rows = {k: v for (tk, k, _, _, v, _, _) in C.flat_rows({t: d}) if tk == t}
    g = lambda k: (rows.get(k) or 0.0) if isinstance(rows.get(k), (int, float)) else 0.0
    has = lambda k: isinstance(rows.get(k), (int, float))
    spot = P["btc_spot"]; hc = P["haircut_pledged_btc"]
    btc_used = adj["btc_used"]; pledged = min(adj["btc_pledged_used"], btc_used)
    free = btc_used - pledged
    btc_mv = (free * spot + pledged * spot * (1 - hc)) / 1e6
    count_known = has("btc_count_bs") or adj["btc_used"] > 0   # ARBK/BTCT: count not disclosed -> carrying value kept
    btc_mv_used = btc_mv if count_known else g("btc_carrying_value")
    # tangible assets
    ta = g("total_assets") - g("goodwill_intangibles") - g("btc_carrying_value") + btc_mv_used + adj["pf_cash"]
    debt_carry = adj["debt_carrying_override"] if adj["debt_carrying_override"] else g("debt_carrying")
    debt_principal = g("debt_principal") - adj["btc_loan_book"] + adj["pf_debt"]
    btc_owed_mv = adj["btc_owed"] * spot / 1e6
    liab = g("total_liabilities") - debt_carry + g("debt_principal") - adj["btc_loan_book"] + btc_owed_mv - adj["warrant_liability"] + adj["pf_debt"]
    senior = g("nci") + g("preferred") + adj["mezzanine_claims"]
    nav_t = ta - liab - senior
    shares = g("basic_shares") + g("rsu") + adj["penny_warrants"] + adj["itm_tsm_shares"] + adj["pf_shares"]
    nav_t_ps = nav_t / shares if shares else None
    if adj["itm_conv_principal"] > 0:
        conv_ps = (nav_t + adj["itm_conv_principal"]) / (shares + adj["itm_conv_shares"])
        nav_t_ps_dil = min(nav_t_ps, conv_ps)
    else:
        conv_ps = None; nav_t_ps_dil = nav_t_ps
    # NAV-M
    eh = g("hashrate_inst") if has("hashrate_inst") and g("hashrate_inst") > 0 else (g("hashrate_op") if has("hashrate_op") else 0.0)
    jth = g("jth") if has("jth") and g("jth") > 0 else None
    fit = curve["fit"] if curve else None
    eligible = adj["ppe_basis"] == "MARK" and eh > 0 and jth is not None and fit is not None
    asic_pth = AD.price_at(fit, jth, curve["params"]) if eligible else None
    asic_mv = eh * asic_pth if eligible else None
    extrap = AD.extrapolated(fit, jth, curve["params"]) if eligible else None
    local_n = AD.local_count(curve["sample"], jth, curve["params"]) if eligible else None
    sparse = (local_n < curve["params"]["min_local"]) if eligible else None
    ask_pth = C.asic_price_per_th(jth, C.ASIC_CURVE) if (adj["ppe_basis"] == "MARK" and eh > 0 and jth is not None) else None
    if eligible:
        infra = g("mw_owned") * P["infra_usd_m_per_mw"] if has("mw_owned") and g("mw_owned") > 0 else (g("ppe_infra_net") if has("ppe_infra_net") else 0.0)
        ppe_marked = asic_mv + infra + g("cip")
        mark_adj = ppe_marked - g("ppe_net_total")
        nav_m = nav_t + mark_adj
    else:
        infra = None; ppe_marked = None; mark_adj = None; nav_m = None
    nav_m_ps = nav_m / shares if (nav_m is not None and shares) else None
    # NAV-L (liquidation stress on NAV-T basis)
    ppe_for_liq = ppe_marked if ppe_marked is not None else g("ppe_net_total")
    liq = (nav_t - (g("equipment_deposits") + g("other_current_assets")) * P["liq_haircut_other_current"]
           - g("investments_other_noncurrent") * P["liq_haircut_other_noncurrent"]
           - (g("ppe_net_total") - ppe_for_liq) - ppe_for_liq * P["liq_haircut_ppe"]
           - g("rou_assets") * P["liq_haircut_rou"] - ta * P["liq_winddown_pct_assets"])
    liq_ps = liq / shares if shares else None
    # market
    price = g("price")
    mcap = price * (g("basic_shares") + adj["pf_shares"])
    ev = mcap + debt_principal + btc_owed_mv + adj["debt_like"] + senior - g("cash") - g("restricted_cash") - adj["pf_cash"] - btc_mv_used
    p_nav = price / nav_t_ps_dil if (nav_t_ps_dil and nav_t_ps_dil > 0) else None
    ev_eh = ev / g("hashrate_op") if has("hashrate_op") and g("hashrate_op") > 0 else None
    book_ps = g("total_equity") / g("basic_shares") if g("basic_shares") else None
    net_btc = btc_used - adj["btc_owed"]
    return dict(btc_used=btc_used, btc_mv=btc_mv_used, tangible_assets=ta, debt_principal_pf=debt_principal, nav_liabilities=liab, senior=senior,
                nav_t=nav_t, shares=shares, nav_t_ps=nav_t_ps, conv_ps=conv_ps, nav_t_ps_dil=nav_t_ps_dil, asic_mv=asic_mv, infra=infra,
                mark_adj=mark_adj, nav_m=nav_m, nav_m_ps=nav_m_ps, nav_l=liq, nav_l_ps=liq_ps, mcap=mcap, ev=ev, p_nav=p_nav, ev_eh=ev_eh,
                book_ps=book_ps, net_btc=net_btc, eligible_m=eligible, asic_pth=asic_pth, ask_pth=ask_pth, extrap=extrap, local_n=local_n, sparse=sparse,
                nav_m_ps_ask=((nav_t + (eh * ask_pth + (infra if infra is not None else 0.0) + g("cip") - g("ppe_net_total"))) / shares if (eligible and shares) else None))


def deal_curve(deals=None, T=None):
    deals = deals if deals is not None else C.load_deals()
    sample, excl, DP = AD.fit_rows(deals, T or C.DATA_CUT, C.DEAL_PARAMS)
    fit = AD.wls(sample, DP)
    return dict(fit=fit, params=DP, sample=sample, excluded=excl, deals=deals)


def run(spot=None):
    comps = C.load_companies(); P = dict(C.PARAMS)
    if spot: P["btc_spot"] = spot
    curve = deal_curve()
    res = {t: compute(t, comps[t], C.ADJ[t], P, curve) for t in C.ORDER}
    return res, comps, P, curve


def compare(res, xlsx, curve=None):
    import openpyxl
    wb = openpyxl.load_workbook(xlsx, data_only=True); ws = wb["NAV"]
    hdr = {ws.cell(5, c).value: c for c in range(1, ws.max_column + 1) if ws.cell(5, c).value}
    tick_row = {ws.cell(r, 1).value: r for r in range(6, ws.max_row + 1) if ws.cell(r, 1).value}
    pairs = [("nav_t", "NAV-T ($m)"), ("nav_t_ps_dil", "NAV-T per share, diluted ($)"), ("nav_m", "NAV-M ($m)"), ("nav_l_ps", "NAV-L per share ($)"),
             ("ev", "EV ($m)"), ("p_nav", "P / NAV-T"), ("shares", "Shares for NAV (m)"), ("btc_mv", "BTC marked value ($m)")]
    out = []; bad = 0
    for t in C.ORDER:
        r = tick_row.get(t)
        for k, h in pairs:
            e = res[t][k]; w = ws.cell(r, hdr[h]).value if (r and h in hdr) else None
            if e is None and (w in (None, "", "n/a")): out.append((t, k, e, w, "OK")); continue
            if e is None or not isinstance(w, (int, float)):
                out.append((t, k, e, w, "MISMATCH")); bad += 1; continue
            ok = abs(e - w) <= max(1e-6, 1e-6 * abs(w))
            bad += (not ok); out.append((t, k, e, w, "OK" if ok else "MISMATCH"))
    if curve is not None and "ASIC_Curve" in wb.sheetnames:   # curve coefficients: engine WLS vs workbook LINEST
        cw = wb["ASIC_Curve"]; lab = {cw.cell(r, 1).value: cw.cell(r, 2).value for r in range(1, cw.max_row + 1) if cw.cell(r, 1).value}
        fit = curve["fit"]
        pairs = [("n (deals in fit)", fit["n"] if fit else 0), ("a (ln $/TH at ref J/TH, T)", fit["a"] if fit else None), ("b (per J/TH)", fit["b"] if fit else None), ("g (per month before T)", fit["g"] if fit else None), ("weighted R²", fit["r2"] if fit else None)]
        for k, e in pairs:
            w = lab.get(k)
            if e is None and (w in (None, "", "n/a")): out.append(("CURVE", k, e, w, "OK")); continue
            if e is None or not isinstance(w, (int, float)): out.append(("CURVE", k, e, w, "MISMATCH")); bad += 1; continue
            ok = abs(e - w) <= max(1e-6, 1e-6 * abs(w)); bad += (not ok); out.append(("CURVE", k, e, w, "OK" if ok else "MISMATCH"))
    return out, bad


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("--xlsx"); ap.add_argument("--json"); ap.add_argument("--spot", type=float)
    a = ap.parse_args()
    res, comps, P, curve = run(a.spot)
    fit = curve["fit"]
    print(f"Mining NAV engine v{ENGINE_VERSION} | data cut {C.DATA_CUT} | BTC spot {P['btc_spot']:,.2f} | fingerprint {C.fingerprint(comps, curve['deals'])[:16]}…")
    if fit: print(f"ASIC deal curve: n={fit['n']} (of {len(curve['deals'])} panel rows; {len(curve['excluded'])} excluded) | $/TH@16J/TH={fit['ref_price']:.2f} | b={fit['b']:.4f}/J | trend {fit['monthly_drift']*100:+.2f}%/mo back | R²={fit['r2']:.3f} | J range {fit['jmin']}–{fit['jmax']} | latest deal {fit['latest_deal']} (+{fit['extrap_months']:.1f} mo to T) | secondary discount {AD.secondary_discount(fit, curve['excluded'], curve['params'])}")
    else: print(f"ASIC deal curve UNAVAILABLE (sample {len(curve['sample'])} < min) — NAV-M not computed")
    print(f"{'Ticker':6s} {'BTC used':>9s} {'NAV-T $m':>10s} {'NAV-T/sh':>9s} {'dil':>7s} {'NAV-M/sh':>9s} {'NAV-L/sh':>9s} {'Price':>8s} {'P/NAV':>6s} {'EV $m':>9s} {'EV/EH':>7s}")
    for t in C.ORDER:
        r = res[t]
        f = lambda v, w=9, p=2: (f"{v:>{w},.{p}f}" if isinstance(v, (int, float)) else f"{'n/a':>{w}s}")
        print(f"{t:6s} {f(r['btc_used'],9,0)} {f(r['nav_t'],10,1)} {f(r['nav_t_ps'],9,3)} {f(r['nav_t_ps_dil'],7,3)} {f(r['nav_m_ps'],9,3)} {f(r['nav_l_ps'],9,3)} {f(comps[t]['market']['price_close_2026_10_15_usd']['value'] if t!='ARBK' else 1.92/2160,8,3)} {f(r['p_nav'],6,2)} {f(r['ev'],9,0)} {f(r['ev_eh'],7,1)}")
    bad = 0
    if a.xlsx:
        out, bad = compare(res, a.xlsx, curve)
        print(f"\nWorkbook compare: {len(out)} values, mismatches {bad}")
        for o in out:
            if o[4] != "OK": print("  ", o)
    if a.json:
        json.dump(dict(engine=ENGINE_VERSION, data_cut=C.DATA_CUT, params=P, deal_params=curve["params"], curve_fit=fit, fingerprint=C.fingerprint(comps, curve["deals"]), results=res), open(a.json, "w"), indent=2, default=str)
    sys.exit(1 if bad else 0)
