# -*- coding: utf-8 -*-
"""
mining_nav_interim.py — Mining NAV Standard v1.2 on an interim data revision (owner rule of 15 Nov 2026).

Between the quarterly re-bases a company's inputs are replaced as soon as a new filing is read; the data cut of the
release (closing prices, BTC spot, FX, ASIC level and slope) stays the same. This script runs the published v1.2
computation (mining_nav_engine.compute with the v1.2 level from mining_nav_v12.py) on one inputs file that carries
both the per-company data and the 17 adjustment fields, so no published script is edited:

  * every company of the inputs file is computed at the three v1.2 anchors (Standard K3 level, daily fixing, v1.1 level);
  * with --base the published inputs file is computed the same way and compared: companies whose data and adjustments
    are unchanged must give identical results (difference 0), revised companies are listed before -> after;
  * with --published the base run is also compared with the published v1.2 results file (difference 0 expected).

Usage: python3 -I mining_nav_interim.py --inputs mining_nav_v1.2_inputs_2026-11-15.json \
           --base mining_nav_v1.1_inputs_2026-10-15.json --published mining_nav_v1.2_results_2026-10-17.json [--json out.json]
Needs, in the same folder: nav_common.py, mining_nav_engine.py, asic_deals.py, mining_nav_v12.py, the deal panel CSV
(asic_deals_panel_2026-10-17.csv) and the K3 series (asic_hashrate_price_ipmk_input_k3_v1.0_2026-10-17.csv).
"""
import sys, os, json, math, hashlib, argparse
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
os.environ.setdefault("NAV_DEALS", os.path.join(HERE, "asic_deals_panel_2026-10-17.csv"))
import nav_common as C
import mining_nav_engine as E
import mining_nav_v12 as V

KEYS = ("nav_t", "nav_t_ps_dil", "nav_m", "nav_m_ps", "nav_l_ps", "asic_pth", "asic_mv", "eligible_m", "p_nav", "ev", "shares", "btc_mv")
OUT_KEYS = ("nav_t_ps_dil", "nav_m", "nav_m_ps", "nav_l_ps", "asic_pth", "asic_mv", "eligible_m", "p_nav")   # as in the published v1.2 results file


def adjustments(inp):
    adj = {}
    for t in C.ORDER:
        a = dict(inp["adjustments"][t])
        for k, _, _ in C.ADJ_FIELDS:
            a.setdefault(k, "" if k in ("ppe_basis", "flags") else 0)
        adj[t] = a
    return adj


def fingerprint(inp):
    """SHA-256 of the canonical JSON of data, adjustments, parameters and the deal panel (same payload as nav_common.fingerprint)."""
    comps, adj = inp["companies"], adjustments(inp)
    payload = {t: {"bs": comps[t]["bs"], "debt": comps[t]["debt"], "shares": comps[t]["shares"], "ops": comps[t]["ops"], "market": comps[t]["market"],
                   "balance_sheet_date": comps[t]["balance_sheet_date"]} for t in C.ORDER}
    s = json.dumps({"version": C.VERSION, "params": C.PARAMS, "deal_params": C.DEAL_PARAMS, "ask_curve": C.ASIC_CURVE, "adj": adj, "data": payload,
                    "deals": C.load_deals()}, sort_keys=True, ensure_ascii=False, default=str)
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def run(inp):
    if inp.get("params") and any(abs(float(inp["params"][k]) - float(v)) > 1e-12 for k, v in C.PARAMS.items()):
        raise SystemExit("inputs file parameters differ from the Standard parameters (nav_common.PARAMS): an interim revision keeps the data cut")
    comps, adj, P = inp["companies"], adjustments(inp), dict(C.PARAMS)
    level, status, n_obs, n_src = V.k3_level()
    curve = E.deal_curve()
    anchors = {"v1.2 primary (Standard K3, %s)" % V.MONTH: level, "sensitivity: Standard daily fixing 2026-10-02": V.FIXING_K3_20261002,
               "v1.1 deal-curve level": math.exp(curve["fit"]["a"])}
    res = {n: {t: E.compute(t, comps[t], adj[t], P, V.with_anchor(curve, a)) for t in C.ORDER} for n, a in anchors.items()}
    return res, anchors, dict(level=level, status=status, n_obs=n_obs, n_src=n_src, b=curve["fit"]["b"])


def changed(a, b, t):
    da = {k: a["companies"][t].get(k) for k in ("balance_sheet_date", "bs", "debt", "shares", "ops", "market")}
    db = {k: b["companies"][t].get(k) for k in ("balance_sheet_date", "bs", "debt", "shares", "ops", "market")}
    return da != db or adjustments(a)[t] != adjustments(b)[t]


def num(x):
    return x if isinstance(x, (int, float)) and not isinstance(x, bool) else None


def fmt(x, d=3):
    return "n/a" if num(x) is None else f"{x:,.{d}f}"


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--inputs", required=True); ap.add_argument("--base"); ap.add_argument("--published"); ap.add_argument("--json")
    a = ap.parse_args()
    inp = json.load(open(a.inputs, encoding="utf-8"))
    res, anchors, info = run(inp)
    names = list(anchors); prim = names[0]
    print(f"Mining NAV v1.2 interim revision | inputs {os.path.basename(a.inputs)} | cut {C.DATA_CUT} | K3 level {info['level']:.2f} ({info['status']}) | slope b={info['b']:.4f}/J")
    print(f"inputs fingerprint SHA-256 {fingerprint(inp)}")
    print(f"{'Ticker':6s} {'BS date':10s} {'NAV-T $m':>10s} {'NAV-T/sh':>9s} {'NAV-M/sh':>9s} {'NAV-L/sh':>9s} {'P/NAV-T':>8s} {'EV $m':>9s}")
    for t in C.ORDER:
        r = res[prim][t]
        print(f"{t:6s} {inp['companies'][t]['balance_sheet_date']:10s} {fmt(r['nav_t'],1):>10s} {fmt(r['nav_t_ps_dil']):>9s} {fmt(r['nav_m_ps']):>9s} {fmt(r['nav_l_ps']):>9s} {fmt(r['p_nav'],2):>8s} {fmt(r['ev'],0):>9s}")
    report = {}
    if a.base:
        base = json.load(open(a.base, encoding="utf-8")); bres, _, _ = run(base)
        rev = [t for t in C.ORDER if changed(inp, base, t)]; same = [t for t in C.ORDER if t not in rev]
        md = 0.0
        for n in names:
            for t in same:
                for k in KEYS:
                    x, y = bres[n][t][k], res[n][t][k]
                    if num(x) is None or num(y) is None:
                        if x != y: md = float("inf")
                    else: md = max(md, abs(x - y))
        print(f"interim check: {len(same)} unchanged companies identical to {os.path.basename(a.base)} at all {len(names)} anchors, max difference {md:.1e}")
        print(f"revised ({len(rev)}): " + ", ".join(rev))
        print(f"{'Ticker':6s} {'BS before':10s} {'BS after':10s} {'NAV-T/sh':>17s} {'NAV-M/sh':>17s} {'NAV-L/sh':>17s} {'P/NAV-T':>13s}")
        for t in rev:
            b0, r = bres[prim][t], res[prim][t]
            print(f"{t:6s} {base['companies'][t]['balance_sheet_date']:10s} {inp['companies'][t]['balance_sheet_date']:10s} "
                  f"{fmt(b0['nav_t_ps_dil']):>8s}->{fmt(r['nav_t_ps_dil']):<8s} {fmt(b0['nav_m_ps']):>8s}->{fmt(r['nav_m_ps']):<8s} "
                  f"{fmt(b0['nav_l_ps']):>8s}->{fmt(r['nav_l_ps']):<8s} {fmt(b0['p_nav'],2):>6s}->{fmt(r['p_nav'],2):<6s}")
        report = dict(base=os.path.basename(a.base), unchanged=same, revised=rev, max_difference_unchanged=md,
                      before={t: {k: bres[prim][t][k] for k in KEYS} for t in rev})
        if a.published:
            pub = json.load(open(a.published, encoding="utf-8"))["results"]; pd = 0.0
            for n in names:
                for t in C.ORDER:
                    for k in OUT_KEYS:
                        x, y = pub[n][t][k], bres[n][t][k]
                        if num(x) is None or num(y) is None:
                            if x != y: pd = float("inf")
                        else: pd = max(pd, abs(x - y))
            print(f"published check: base inputs reproduce {os.path.basename(a.published)} ({len(C.ORDER)} companies x {len(names)} anchors x {len(OUT_KEYS)} values), max difference {pd:.1e}")
            report["published"] = os.path.basename(a.published); report["max_difference_published"] = pd
    if a.json:
        json.dump(dict(engine="1.2 interim", inputs_file=os.path.basename(a.inputs), inputs_fingerprint=fingerprint(inp), data_cut=C.DATA_CUT,
                       k3_level=info["level"], status=info["status"], slope_b=info["b"], anchors=anchors, revision=inp.get("revision"), check=report,
                       balance_sheet_dates={t: inp["companies"][t]["balance_sheet_date"] for t in C.ORDER},
                       results={n: {t: {k: res[n][t][k] for k in KEYS} for t in C.ORDER} for n in names}),
                  open(a.json, "w", encoding="utf-8"), indent=1, default=str)


if __name__ == "__main__":
    main()
