# -*- coding: utf-8 -*-
"""
mining_nav_v12.py — Mining NAV Standard v1.2: NAV-M and NAV-L re-anchored to the ASIC Hashrate Price Standard v1.0.

Rule (v1.2): machine price at fleet efficiency j (J/TH) = L * exp(b * (j - 16)),
  L = K3 (14-19 J/TH) class value of the ASIC Hashrate Price Standard for the month of the data cut (extended contour A+B+C),
  b = slope per J/TH fitted on the primary-market deal panel (NAV v1.1, 21 deals).
v1.1 anchored the level to the same deal fit extrapolated 8 months past the last deal; v1.2 takes the level from the market series.
Everything else (NAV-T, adjustments, infrastructure value, haircuts) is unchanged and reused from mining_nav_engine.py.

Usage: NAV_DATA_DIR=<dir with per-company JSON and asic_deals/> python3 -I mining_nav_v12.py [--json out.json]
"""
import sys, os, csv, json, math, argparse
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nav_common as C
import mining_nav_engine as E

HERE = os.path.dirname(os.path.abspath(__file__))
IPMK = os.path.join(HERE, "asic_hashrate_price_ipmk_input_k3_v1.0_2026-10-17.csv")
MONTH = "2026-09"              # month of the data cut (2026-10-15): latest complete month of the Standard series
FIXING_K3_20261002 = 9.19      # Standard v1.0 daily fixing, 2026-10-02, class K3 (sensitivity only)
ENGINE_VERSION = "1.2"


def k3_level(month=MONTH, path=IPMK):
    for r in csv.DictReader(open(path, encoding="utf-8")):
        if r["month"] == month:
            return float(r["price_usd_per_th"]), r["status"], int(r["n_obs"]), int(r["n_sources"])
    raise SystemExit(f"month {month} not in {path}")


def with_anchor(curve, level):
    fit = dict(curve["fit"]); fit["a"] = math.log(level); fit["ref_price"] = level
    return dict(curve, fit=fit)


def run(anchor):
    comps = C.load_companies(); P = dict(C.PARAMS); curve = E.deal_curve()
    c2 = with_anchor(curve, anchor)
    return {t: E.compute(t, comps[t], C.ADJ[t], P, c2) for t in C.ORDER}, comps, curve


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--json"); a = ap.parse_args()
    level, status, n_obs, n_src = k3_level()
    v11, comps, curve = run(math.exp(curve_a := E.deal_curve()["fit"]["a"]))
    anchors = {"v1.2 primary (Standard K3, %s)" % MONTH: level, "sensitivity: Standard daily fixing 2026-10-02": FIXING_K3_20261002, "v1.1 deal-curve level": math.exp(curve_a)}
    out = {k: run(v)[0] for k, v in anchors.items()}
    b = curve["fit"]["b"]
    print(f"Mining NAV engine v{ENGINE_VERSION} | cut {C.DATA_CUT} | K3 level {level:.2f} ({status}, {n_obs} obs, {n_src} source) | slope b={b:.4f}/J (deal fit n={curve['fit']['n']})")
    print("Class check (v1.2 curve vs Standard 2026-09 classes): K2@13.5 J %.2f vs 12.80 | K3@16 J %.2f vs 7.05 | K4@21.5 J %.2f vs 5.70 | K1@10 J %.2f vs 22.90 (1 obs)" % tuple(level * math.exp(b * (j - 16)) for j in (13.5, 16, 21.5, 10)))
    names = list(anchors)
    print(f"{'Ticker':6s} {'J/TH':>5s} {'$/TH':>6s} " + " ".join(f"{'NAV-M/sh':>9s} {'NAV-L/sh':>9s}" for _ in names))
    for t in C.ORDER:
        r0 = out[names[0]][t]
        if not r0["eligible_m"]: continue
        jj = 16 + math.log(r0['asic_pth'] / level) / b
        row = f"{t:6s} {jj:>5.1f} {r0['asic_pth']:>6.2f} " + " ".join(f"{out[n][t]['nav_m_ps']:>9.3f} {out[n][t]['nav_l_ps']:>9.3f}" for n in names)
        print(row)
    # self-check: the v1.1-level column must reproduce the published v1.1 NAV-M per share
    pub = {"RIOT": 4.594, "CLSK": 1.855, "ABTC": 10.393}
    bad = [t for t, v in pub.items() if abs(out[names[2]][t]["nav_m_ps"] - v) > 0.0006]
    print("v1.1 reproduction check:", "OK (RIOT 4.594, CLSK 1.855, ABTC 10.393)" if not bad else f"MISMATCH {bad}")
    if a.json:
        json.dump(dict(engine=ENGINE_VERSION, data_cut=C.DATA_CUT, k3_level=level, status=status, slope_b=b, anchors=anchors,
                       results={n: {t: {k: out[n][t][k] for k in ("nav_t_ps_dil", "nav_m", "nav_m_ps", "nav_l_ps", "asic_pth", "asic_mv", "eligible_m", "p_nav")} for t in C.ORDER} for n in names}), open(a.json, "w"), indent=1, default=str)


if __name__ == "__main__":
    main()
