# -*- coding: utf-8 -*-
"""
validate_nav_interim.py — second, independent computation for a Mining NAV interim data revision.

Re-implements the NAV formulas of the Standard (page "The five NAV levels") directly on the inputs file, without importing
nav_common / mining_nav_engine, and compares NAV-T, NAV-T per diluted share, NAV-M per share, NAV-L per share, EV and
P/NAV-T with the results file written by mining_nav_interim.py --json. The machine price uses the published v1.2 rule
L * exp(b * (J/TH - 16)) with L read from the K3 series CSV and b from the results file (deal-fit slope).

Usage: python3 -I validate_nav_interim.py --inputs mining_nav_v1.2_inputs_2026-11-15.json --results mining_nav_v1.2_results_2026-11-15.json
Exit code 0 = every value within 1e-9 (relative) of the engine.
"""
import sys, os, csv, json, math, argparse

ADJ0 = dict(btc_used=0, btc_pledged_used=0, btc_owed=0, btc_loan_book=0, warrant_liability=0, penny_warrants=0, itm_tsm_shares=0, itm_conv_principal=0,
            itm_conv_shares=0, mezzanine_claims=0, debt_carrying_override=0, debt_like=0, pf_cash=0, pf_debt=0, pf_shares=0, ppe_basis="", flags="")


def v(o):
    if isinstance(o, dict): o = o.get("value")
    return None if o in (None, "") else float(o)


def z(o):
    x = v(o); return 0.0 if x is None else x


def debt(d):
    p = c = 0.0
    for e in d["debt"]:
        n = str(e.get("instrument", ""))
        if n.startswith("[") or n.upper().startswith("MEMO") or "NOT IN TOTAL" in n.upper() or "EXCLUDED" in n.upper(): continue
        pr = 0.0 if e.get("principal") in (None, "") else float(e["principal"])
        ca = pr if e.get("carrying") in (None, "") else float(e["carrying"])
        p += pr; c += ca
    return p, c


def nav(t, d, a, P, level, b):
    bs, sh, ops = d["bs"], d["shares"], d["ops"]
    spot = P["btc_spot"]
    used = a["btc_used"]; pl = min(a["btc_pledged_used"], used)
    mv = ((used - pl) * spot + pl * spot * (1 - P["haircut_pledged_btc"])) / 1e6
    if v(bs.get("btc_count_bs")) is None and not used > 0: mv = z(bs.get("btc_carrying_value"))
    ta = z(bs.get("total_assets")) - z(bs.get("goodwill_intangibles")) - z(bs.get("btc_carrying_value")) + mv + a["pf_cash"]
    dp, dc = debt(d)
    carry = a["debt_carrying_override"] or dc
    owed = a["btc_owed"] * spot / 1e6
    liab = z(bs.get("total_liabilities")) - carry + dp - a["btc_loan_book"] + owed - a["warrant_liability"] + a["pf_debt"]
    senior = z(bs.get("noncontrolling_interest")) + z(bs.get("preferred_liquidation_preference")) + a["mezzanine_claims"]
    nav_t = ta - liab - senior
    basic = z(sh.get("basic_outstanding")) / 1e6
    if t == "ARBK": basic /= 2160.0                       # ADS equivalents (price is per ADS)
    shares = basic + z(sh.get("rsu_unvested")) / 1e6 + a["penny_warrants"] + a["itm_tsm_shares"] + a["pf_shares"]
    ps = nav_t / shares
    dil = min(ps, (nav_t + a["itm_conv_principal"]) / (shares + a["itm_conv_shares"])) if a["itm_conv_principal"] > 0 else ps
    eh = z(ops.get("hashrate_ehs_installed")) or z(ops.get("hashrate_ehs_operating"))
    j = v(ops.get("fleet_efficiency_jth")); j = j if j and j > 0 else None
    ppe = z(bs.get("ppe_net_total")); marked = None; nav_m = None
    if a["ppe_basis"] == "MARK" and eh > 0 and j is not None:
        mw = v(ops.get("energized_mw_owned"))
        infra = mw * P["infra_usd_m_per_mw"] if mw and mw > 0 else z(bs.get("ppe_land_buildings_infra_net"))
        marked = eh * level * math.exp(b * (j - 16.0)) + infra + z(bs.get("construction_in_progress"))
        nav_m = nav_t + marked - ppe
    liq_ppe = marked if marked is not None else ppe
    nav_l = (nav_t - (z(bs.get("equipment_deposits")) + z(bs.get("other_current_assets"))) * P["liq_haircut_other_current"]
             - z(bs.get("investments_other_noncurrent")) * P["liq_haircut_other_noncurrent"] - (ppe - liq_ppe) - liq_ppe * P["liq_haircut_ppe"]
             - z(bs.get("rou_assets")) * P["liq_haircut_rou"] - ta * P["liq_winddown_pct_assets"])
    price = z(d["market"].get("price_close_2026_10_15_usd"))
    ev = (price * (basic + a["pf_shares"]) + dp - a["btc_loan_book"] + a["pf_debt"] + owed + a["debt_like"] + senior
          - z(bs.get("cash")) - z(bs.get("restricted_cash")) - a["pf_cash"] - mv)
    return dict(nav_t=nav_t, nav_t_ps_dil=dil, nav_m_ps=(nav_m / shares if nav_m is not None else None), nav_l_ps=nav_l / shares, ev=ev,
                p_nav=(price / dil if dil > 0 else None))


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--inputs", required=True); ap.add_argument("--results", required=True)
    ap.add_argument("--k3", default="asic_hashrate_price_ipmk_input_k3_v1.0_2026-10-17.csv"); ap.add_argument("--month", default="2026-09")
    a = ap.parse_args()
    here = os.path.dirname(os.path.abspath(__file__))
    inp = json.load(open(a.inputs, encoding="utf-8")); res = json.load(open(a.results, encoding="utf-8"))
    k3 = os.path.join(here, a.k3) if not os.path.exists(a.k3) else a.k3
    level = next(float(r["price_usd_per_th"]) for r in csv.DictReader(open(k3, encoding="utf-8")) if r["month"] == a.month)
    prim = next(n for n in res["results"] if n.startswith("v1.2 primary"))
    P = inp["params"]; b = res["slope_b"]; n = bad = 0
    for t, d in inp["companies"].items():
        adj = dict(ADJ0, **inp["adjustments"][t])
        mine = nav(t, d, adj, P, level, b); eng = res["results"][prim][t]
        for k, x in mine.items():
            y = eng.get(k); n += 1
            ok = (x is None and y is None) or (x is not None and y is not None and abs(x - y) <= 1e-9 * max(1.0, abs(y)))
            if not ok: bad += 1; print(f"MISMATCH {t} {k}: independent {x} vs engine {y}")
    print(f"validate_nav_interim: K3 level {level:.2f} ({a.month}), slope {b:.6f}; {len(inp['companies'])} companies, {n} values compared, {bad} mismatches")
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()
