# -*- coding: utf-8 -*-
"""
clsk_valuation_engine.py — independent recomputation engine for the CLSK Fair Value Model v4.0.

The engine reads the Assumptions sheet (and the few Historical / NAV facts the model uses),
recomputes every headline output from first principles — no Excel formulas are evaluated —
and compares them with the workbook's cached values. It is the reproducibility layer of the
HASHFLOPS Equity Valuation & Publication Standard.

Usage
  python3 -I clsk_valuation_engine.py MODEL.xlsx                 # recompute + compare
  python3 -I clsk_valuation_engine.py MODEL.xlsx --json out.json # also dump results
  python3 -I clsk_valuation_engine.py MODEL.xlsx --override Base.27=0.12 --override Base.29=0.30
        # scenario what-ifs: <Bear|Base|Bull|All>.<Assumptions row>=<value>
  python3 -I clsk_valuation_engine.py MODEL.xlsx --inputs-json inputs.json   # export inputs + sha256

Engine version 4.0 (2026-10-16). Mirrors model v4.0 exactly; any deliberate model change must be
reflected here and bump the version in Version Log!B10.
"""
import sys, json, hashlib, datetime as dt, argparse
import openpyxl

ENGINE_VERSION = "4.0"
SC = {"Bear": "C", "Base": "D", "Bull": "E"}
YEARS_M = list(range(2027, 2033))
YEARS_H = list(range(2026, 2049))


# ----------------------------------------------------------------------------- inputs
class Inputs:
    """All inputs as a dict {row: {C:..., D:..., E:...}} taken from the Assumptions sheet (cached values)."""
    def __init__(self, path):
        self.path = path
        wbv = openpyxl.load_workbook(path, data_only=True)
        self.wbv = wbv
        A = wbv["Assumptions"]
        self.rows = {}
        for r in range(6, 125):
            self.rows[r] = {c: A[f"{c}{r}"].value for c in "CDE"}
        H = wbv["Historical"]
        self.hist = {"sept_btc": H["H21"].value, "sept_hash": H["H22"].value}
        N = wbv["NAV"]
        self.nav_raw = {r: N[f"B{r}"].value for r in list(range(20, 42)) + [89, 90, 104, 105, 106, 107, 108, 109, 110]}
        self.nav_cip = N["B26"].value

    def a(self, row, col):
        v = self.rows[row][col]
        return v

    def override(self, spec):
        sc, rest = spec.split(".", 1); row, val = rest.split("="); row = int(row)
        try: val = float(val)
        except ValueError: pass
        cols = ["C", "D", "E"] if sc == "All" else [SC[sc]]
        for c in cols: self.rows[row][c] = val
        # linked scenario columns (C/E = $D$) for single-value facts
        if sc == "Base" and row in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 26, 32, 48, 49, 50, 51, 53, 58, 59, 60, 62, 63, 66, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 102, 103, 104, 105, 107, 108, 110, 111, 116, 117, 118):
            self.rows[row]["C"] = val; self.rows[row]["E"] = val

    def fingerprint(self):
        payload = {str(r): {c: (v.isoformat() if isinstance(v, (dt.date, dt.datetime)) else v) for c, v in d.items()} for r, d in self.rows.items()}
        s = json.dumps(payload, sort_keys=True, ensure_ascii=False, default=str)
        return hashlib.sha256(s.encode("utf-8")).hexdigest(), payload


def to_date(v):
    return v.date() if isinstance(v, dt.datetime) else v


# ----------------------------------------------------------------------------- model
class Model:
    def __init__(self, inp: Inputs):
        self.i = inp
        self.val = to_date(inp.a(84, "D"))
        self.timing = inp.a(110, "D")
        self.halving = to_date(inp.a(111, "D"))

    def a(self, row, col): return self.i.a(row, col)

    def t(self, y):
        jan1 = dt.date(y, 1, 1); dec31 = dt.date(y, 12, 31)
        return max(0.0, (jan1 - self.val).days / 365.25) + self.timing * ((dec31 - max(jan1, self.val)).days + 1) / 365.25

    def shares_val(self, c):
        return self.a(7, c) + self.a(116, "D") * self.a(117, "D") + self.a(118, "D")

    # ---- mining (segment, regime-1 tax)
    def mining(self, sc, hp_static=None, btc_spot=None):
        c = SC[sc]
        spot = btc_spot if btc_spot is not None else self.a(15, c)
        cagr = self.a(27, c); decl = self.a(28, c); shock = self.a(29, c); prod0 = self.a(26, c)
        pwr0 = self.a(30, c); pwr_esc = self.a(31, c); eff0 = self.a(32, c); eff32 = self.a(33, c)
        opex0 = self.a(34, c); opex_inf = self.a(35, c); sus = self.a(36, c); r = self.a(37, c); salvage = self.a(38, c)
        tax = self.a(88, c); da_mult = self.a(97, c)
        rows = {}; pv_fcf = pv_tax = pv_rev = 0.0
        hy = self.halving.year
        for y in YEARS_M:
            te = y - 2026
            price = spot * (1 + cagr) ** te
            if y > hy: hf = 1 - shock
            elif y == hy: hf = 1 - shock * ((dt.date(y, 12, 31) - self.halving).days + 1) / ((dt.date(y, 12, 31) - dt.date(y, 1, 1)).days + 1)
            else: hf = 1.0
            prod = prod0 * (1 - decl) ** te * hf
            hr = self.a(40 + (y - 2027), c)
            btc = hr * prod * 365
            rev = (hp_static * hr * 365 / 1000) if hp_static is not None else btc * price / 1e6
            eff = eff0 + (eff32 - eff0) * (y - 2027) / 5
            energy = hr * eff * 8760 * pwr0 * (1 + pwr_esc) ** te / 1000
            opex = opex0 * (1 + opex_inf) ** (y - 2027)
            ebitda = rev - energy - opex
            capex = hr * sus; da = capex * da_mult
            ctax = max(0.0, ebitda - da) * tax
            fcf = ebitda - capex - ctax
            df = 1 / (1 + r) ** self.t(y)
            pv_fcf += fcf * df; pv_tax += ctax * df; pv_rev += rev * df
            rows[y] = dict(price=price, prod=prod, btc=btc, rev=rev, energy=energy, opex=opex, ebitda=ebitda, capex=capex, da=da, tax1=ctax, fcf=fcf, df=df, hashprice=price * prod / 1000)
        pv_salv = salvage * rows[2032]["df"]
        return dict(ev=max(0.0, pv_fcf + pv_salv), pv_fcf=pv_fcf, pv_tax=pv_tax, pv_salv=pv_salv, rows=rows)

    # ---- HPC (segment, regime-1 tax)
    def hpc(self, sc):
        c = SC[sc]
        mw = self.a(48, c); capex_mw = self.a(52, c); noi_m = self.a(54, c); r = self.a(55, c); prob = self.a(56, c)
        ph = {2026: self.a(58, c), 2027: self.a(59, c), 2028: self.a(60, c)}; credit = self.a(83, c); tax = self.a(88, c); life = self.a(89, c)
        esc = self.a(53, c); last = self.a(94, c); first_full = self.a(99, c); total_rent = self.a(50, c)
        total_capex = mw * capex_mw
        rent = {}
        for y in YEARS_H:
            if y <= 2026: rent[y] = 0.0
            elif y == 2027: rent[y] = self.a(91, c)
            elif y == 2028: rent[y] = self.a(92, c)
            elif y < last: rent[y] = self.a(93, c) * (1 + esc) ** (y - first_full)
            elif y == last: rent[y] = total_rent - sum(rent.values())
            else: rent[y] = 0.0
        comm_year = to_date(self.a(96, "D")).year
        rows = {}; pv_noi = pv_capex = pv_tax = pv_capex_full = 0.0
        for y in YEARS_H:
            df = 1 / (1 + r) ** self.t(y)
            noi = rent[y] * noi_m
            cap = max(0.0, total_capex - credit) * ph.get(y, 0.0)
            dep = total_capex / life if y >= comm_year else 0.0
            tx = max(0.0, noi - dep) * tax
            pv_noi += noi * df; pv_capex += cap * df; pv_tax += tx * df; pv_capex_full += total_capex * ph.get(y, 0.0) * df
            rows[y] = dict(rent=rent[y], noi=noi, capex=cap, tax1=tx, df=df)
        pretax = pv_noi - pv_capex
        per_mw_full = ((pv_noi - pv_capex_full) - pv_tax) * prob / mw   # Texas scaling basis (no Sandersville-specific credit)
        return dict(total_capex=total_capex, pv_noi=pv_noi, pv_capex=pv_capex, pretax=pretax, pv_tax=pv_tax,
                    aftertax=pretax - pv_tax, risk_adj=(pretax - pv_tax) * prob, prob=prob, rows=rows, mw=mw, per_mw_full=per_mw_full)

    # ---- notes interest schedule (semi-annual, 30/360, DSCR-sculpted amortisation) — mirrors HPC Project rows 61-69
    def notes_interest_by_year(self, hpc_rows):
        D = "D"
        principal = self.a(74, D); coupon = self.a(62, D); issue = to_date(self.a(80, D)); maturity = to_date(self.a(81, D))
        comm = to_date(self.a(96, D)); dscr = self.a(79, D)
        dates = [issue] + [dt.date(y, m, 1) for y in range(2027, 2032) for m in (4, 10)]
        dates = [d for d in dates if d <= maturity]
        noi = {y: hpc_rows[y]["noi"] for y in YEARS_H}
        def yf(d0, d1): return ((d1.year - d0.year) * 360 + (d1.month - d0.month) * 30 + min(d1.day, 30) - min(d0.day, 30)) / 360
        bal = principal; by_year = {}
        for k in range(1, len(dates)):
            d0, d1 = dates[k - 1], dates[k]
            # trailing 6-month NOI proxy as in the workbook: first coupon (prev year+this)/4, Oct = this/2, Apr = (prev+this)/4
            if k == 1: proxy = (noi[2026] + noi[2027]) / 4
            elif d1.month == 10: proxy = noi[d1.year] / 2
            else: proxy = (noi[d1.year - 1] + noi[d1.year]) / 4
            cpn = bal * coupon * yf(d0, d1)
            amort = 0.0 if (d1 - comm).days <= 15 else min(bal, max(0.0, proxy / dscr - cpn))
            by_year[d1.year] = by_year.get(d1.year, 0.0) + cpn
            bal = bal - amort
            if d1 == maturity: bal = 0.0
        return by_year

    # ---- consolidated taxes (regime 2) and PV adjustments
    def tax_adjustment(self, sc, mining, hpc):
        c = SC[sc]
        rate = self.a(109, c); nol_lim = self.a(105, c); bonus = self.a(106, c); int_lim = self.a(107, c); life = self.a(89, c)
        comm_year = to_date(self.a(96, "D")).year
        interest = self.notes_interest_by_year(self.hpc("Base")["rows"])  # workbook schedule is Base-only (HPC Project rows 61-69)
        if self.a(108, "D") == 1:
            pass  # not modelled (default 0)
        total_capex_spent = sum(hpc["rows"][y]["capex"] for y in YEARS_H)
        nol = self.a(103, c) + self.a(104, c)
        pv2 = pv1 = 0.0; tax2_27_31 = tax1_27_31 = 0.0; nol_2032 = None; detail = {}
        for y in YEARS_H:
            m = mining["rows"].get(y)
            m_ebitda = m["ebitda"] if m else 0.0; m_da = m["da"] if m else 0.0; m_tax1 = m["tax1"] if m else 0.0; m_df = m["df"] if m else 0.0
            h = hpc["rows"][y]
            dep2 = (bonus * total_capex_spent if y == comm_year else 0.0) + ((1 - bonus) * total_capex_spent / life if comm_year <= y < comm_year + life else 0.0)
            intr = interest.get(y, 0.0)
            ebitda163 = m_ebitda + h["noi"]
            ded_int = min(intr, max(0.0, int_lim * ebitda163))
            ti = (m_ebitda - m_da) + (h["noi"] - dep2) - ded_int
            gen = max(0.0, -ti); used = min(nol, max(0.0, ti) * nol_lim)
            nol = nol + gen - used
            tax2 = (max(0.0, ti) - used) * rate
            tax1 = m_tax1 + h["tax1"]
            share = 0.0 if tax1 == 0 else m_tax1 / tax1
            df = share * m_df + (1 - share) * h["df"]
            pv2 += (tax1 - tax2) * df; pv1 += tax1 * df
            if 2027 <= y <= 2031: tax2_27_31 += tax2; tax1_27_31 += tax1
            if y == 2032: nol_2032 = nol
            detail[y] = dict(ti=ti, nol_close=nol, tax2=tax2, tax1=tax1, df=df)
        return dict(pv_saving_r2=pv2, pv_tax_r1=pv1, nol_2032=nol_2032, nol_final=nol, tax2_27_31=tax2_27_31, tax1_27_31=tax1_27_31, detail=detail)

    def corp_pv(self, sc, mining):
        c = SC[sc]
        base = self.a(112, c); chg = self.a(113, c); post = self.a(114, c); r_post = self.a(115, c); last = self.a(94, "D")
        pv = sum(base * (1 + chg) ** (y - 2027) * mining["rows"][y]["df"] for y in YEARS_M)
        n = last - 2032
        ann = (1 - (1 + r_post) ** (-n)) / r_post * mining["rows"][2032]["df"]
        return pv + post * ann

    def stub(self):
        days = (dt.date(2026, 12, 31) - self.val).days
        btc_day = self.i.hist["sept_btc"] / 30; hr = self.i.hist["sept_hash"]
        rev = btc_day * days * self.a(15, "D") / 1e6
        energy = hr * self.a(32, "D") * 24 * days * self.a(30, "D") / 1000
        opex = self.a(34, "D") * days / 365; capex = self.a(36, "D") * hr * days / 365
        corp = self.a(112, "D") * days / 365
        return rev - energy - opex - capex - corp

    def dilute(self, p0, c):
        N = self.shares_val(c); d30 = self.a(10, c); cp30 = self.a(11, c); cap = self.a(12, c); d32 = self.a(13, c); cp32 = self.a(14, c)
        if p0 <= cp32: return max(0.0, p0)
        p2 = (p0 * N + d32) / (N + d32 / cp32)
        if p2 <= cap: return max(0.0, p2)
        return max(0.0, (p0 * N + d30 + d32 + d30 / cp30 * (cap - cp30)) / (N + d30 / cp30 + d32 / cp32))

    def sotp(self, sc, regime=None, btc_spot=None, texas_prob=None, mining_ev=None):
        c = SC[sc]
        regime = int(self.a(102, "D")) if regime is None else regime
        spot = btc_spot if btc_spot is not None else self.a(15, c)
        treasury = ((self.a(16, c) - self.a(17, c)) * spot + self.a(17, c) * spot * (1 - self.a(18, c))) / 1e6
        cash = self.a(8, c) + self.a(74, c) * (self.a(75, c) - self.a(76, c)) + self.a(82, c)
        debt = -(self.a(90, c) + self.a(74, c))
        m = self.mining(sc, btc_spot=btc_spot); h = self.hpc(sc)
        mev = m["ev"] if mining_ev is None else mining_ev
        per_mw = max(0.0, h["per_mw_full"])
        texas_max = self.a(66, c) * self.a(67, c) * per_mw * self.a(69, c)
        tp = self.a(68, c) if texas_prob is None else texas_prob
        texas = texas_max * tp
        other = self.a(71, c); corp = -self.corp_pv(sc, m)
        tx = self.tax_adjustment(sc, m, h)
        adj = {1: 0.0, 2: tx["pv_saving_r2"], 3: tx["pv_tax_r1"]}[regime]
        stub = self.stub()
        eq = treasury + cash + debt + mev + h["risk_adj"] + texas + other + corp + adj + stub
        p0 = max(0.0, eq / self.shares_val(c))
        fv = self.dilute(p0, c)
        return dict(treasury=treasury, cash=cash, debt=debt, mining=mev, hpc=h["risk_adj"], texas=texas, texas_max=texas_max, other=other,
                    corp=corp, adj=adj, stub=stub, equity=eq, p0=p0, fv=fv, weight=self.a(19, c), m=m, h=h, tx=tx)

    def nav(self):
        v = self.i.nav_raw; D = "D"
        spot = self.a(15, D); btc = self.a(16, D); coll = self.a(17, D); hair = self.a(18, D); shares = self.a(7, D)
        cash = v[20] + self.a(74, D) * (self.a(75, D) - self.a(76, D)) - self.a(77, D) + self.a(82, D)
        dsra = v[21] + self.a(77, D)
        btc_free = (btc - coll) * spot / 1e6; btc_coll = coll * spot / 1e6
        land = v[24]; ppe = v[110] - v[24] - v[26]; cip = v[26]
        other_assets = v[27] + v[28] + v[29] + v[30] + v[31]; gw = v[32] + v[33]
        assets = cash + dsra + btc_free + btc_coll + land + ppe + cip + other_assets + gw
        debt = self.a(90, D) + self.a(74, D); other_liab = v[37] + v[38] + v[39] + v[40] + v[41]; pref = v[89] * v[90]
        nav_pf = assets - debt - other_liab - pref; tangible = nav_pf - gw; disc = tangible - btc_coll * hair
        return dict(pro_forma_ps=nav_pf / shares, tangible_ps=tangible / shares, disc_ps=disc / shares)

    def required_hashprice(self, target_price):
        base = self.sotp("Base"); non_mining = base["equity"] - base["mining"]
        def price_at(hp):
            ev = self.mining("Base", hp_static=hp)["ev"]
            return self.dilute(max(0.0, (non_mining + ev) / self.shares_val("D")), "D")
        lo, hi = 0.0, self.a(95, "D")
        for _ in range(36):
            mid = (lo + hi) / 2
            if price_at(mid) < target_price: lo = mid
            else: hi = mid
        hp = (lo + hi) / 2
        cur = self.a(85, "D")
        return dict(required=hp, fv_at_current_hp=price_at(cur), ev_at_current_hp=self.mining("Base", hp_static=cur)["ev"])

    def run(self):
        out = {}
        for sc in SC:
            s = self.sotp(sc)
            out[sc] = {k: v for k, v in s.items() if k not in ("m", "h", "tx")}
            out[sc]["mining_pv_tax"] = s["m"]["pv_tax"]; out[sc]["hpc_pretax"] = s["h"]["pretax"]; out[sc]["hpc_pv_tax"] = s["h"]["pv_tax"]
            out[sc]["tax"] = {k: v for k, v in s["tx"].items() if k != "detail"}
            out[sc]["hashprice_path"] = {y: s["m"]["rows"][y]["hashprice"] for y in YEARS_M}
            out[sc]["fv_by_regime"] = {}
            for k in (1, 2, 3):
                out[sc]["fv_by_regime"][k] = self.sotp(sc, regime=k)["fv"]
        out["weighted_fv"] = sum(out[sc]["fv"] * out[sc]["weight"] for sc in SC)
        out["weighted_by_regime"] = {k: sum(out[sc]["fv_by_regime"][k] * out[sc]["weight"] for sc in SC) for k in (1, 2, 3)}
        price = self.a(6, "D"); mcap = price * self.a(7, "D"); b = out["Base"]
        out["price"] = price; out["upside"] = out["weighted_fv"] / price - 1
        out["implied_texas_prob"] = (mcap - (b["equity"] - b["texas"])) / b["texas_max"]
        out["mnav_economic"] = (mcap - b["debt"] - b["cash"]) / b["treasury"]
        out["nav"] = self.nav(); out["hashprice"] = self.required_hashprice(price)
        out["shares_val"] = self.shares_val("D"); out["regime"] = int(self.a(102, "D"))
        return out


# ----------------------------------------------------------------------------- compare with workbook
def compare(out, inp: Inputs, tol_rel=1e-6, tol_abs=1e-6):
    w = inp.wbv; S = w["SOTP"]; MM = w["Mining Model"]; HP = w["HPC Project"]; MN = w["mNAV"]; NV = w["NAV"]; HS = w["Hashprice Sens."]; AD = w["Adjustments"]; PS = w["Public Summary"]
    # locate rows on Adjustments / Public Summary by label
    def find(ws, text, col="A"):
        for r in range(1, ws.max_row + 1):
            v = ws[f"{col}{r}"].value
            if isinstance(v, str) and v.startswith(text): return r
        raise KeyError(text)
    r_sel = find(AD, "Выбранная корректировка"); r_r2 = find(AD, "PV экономии: режим 2"); r_r1 = find(AD, "PV налога режима 1 — сегментные")
    r_reg1 = find(PS, "1 — conditional"); r_reg2 = r_reg1 + 1; r_reg3 = r_reg1 + 2
    checks = []
    for sc, col, b in (("Bear", "C", "B"), ("Base", "D", "C"), ("Bull", "E", "D")):
        o = out[sc]; mm_ev = {"Bear": "N10", "Base": "O10", "Bull": "P10"}[sc]; mm_tax = {"Bear": "N14", "Base": "O14", "Bull": "P14"}[sc]
        hp_np = {"Bear": "E27", "Base": "F27", "Bull": "G27"}[sc]; hp_pt = {"Bear": "E25", "Base": "F25", "Bull": "G25"}[sc]
        checks += [(f"{sc} mining EV", o["mining"], MM[mm_ev].value), (f"{sc} mining PV tax (regime 1)", o["mining_pv_tax"], MM[mm_tax].value),
                   (f"{sc} HPC pre-tax NPV", o["hpc_pretax"], HP[hp_pt].value), (f"{sc} HPC risk-adjusted NPV", o["hpc"], HP[hp_np].value),
                   (f"{sc} Texas option", o["texas"], S[f"{b}13"].value), (f"{sc} corporate overhead PV", o["corp"], S[f"{b}15"].value),
                   (f"{sc} tax regime adjustment", o["adj"], S[f"{b}33"].value), (f"{sc} PV saving regime 2", o["tax"]["pv_saving_r2"], AD[f"{col}{r_r2}"].value),
                   (f"{sc} PV tax regime 1 (consolidated tie)", o["tax"]["pv_tax_r1"], AD[f"{col}{r_r1}"].value),
                   (f"{sc} equity pre-conversion", o["equity"], S[f"{b}16"].value), (f"{sc} fair value / share", o["fv"], S[f"{b}25"].value),
                   (f"{sc} FV regime 1", o["fv_by_regime"][1], PS[f"{b}{r_reg1}"].value), (f"{sc} FV regime 3", o["fv_by_regime"][3], PS[f"{b}{r_reg3}"].value)]
    checks += [("Stub cash flow", out["Base"]["stub"], S["C34"].value), ("Weighted FV", out["weighted_fv"], S["G6"].value),
               ("Weighted FV regime 1", out["weighted_by_regime"][1], PS[f"E{r_reg1}"].value), ("Weighted FV regime 3", out["weighted_by_regime"][3], PS[f"E{r_reg3}"].value),
               ("Implied Texas probability", out["implied_texas_prob"], S["G10"].value), ("Economic EV mNAV", out["mnav_economic"], MN["B20"].value),
               ("Tangible NAV / share", out["nav"]["tangible_ps"], NV["B9"].value), ("NAV with BTC discount / share", out["nav"]["disc_ps"], NV["B10"].value),
               ("Required static hashprice", out["hashprice"]["required"], HS["B15"].value), ("FV at current hashprice", out["hashprice"]["fv_at_current_hp"], HS["B14"].value),
               ("Mining EV at current hashprice", out["hashprice"]["ev_at_current_hp"], HS["B13"].value), ("Valuation shares (TSM)", out["shares_val"], w["Assumptions"]["D119"].value)]
    res = []; bad = 0
    for name, p, wv in checks:
        if wv is None: res.append((name, p, None, None, "NO CACHED VALUE")); bad += 1; continue
        d = p - wv; ok = abs(d) <= max(tol_abs, tol_rel * abs(wv))
        bad += (not ok); res.append((name, p, wv, d, "OK" if ok else "MISMATCH"))
    return res, bad


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("xlsx"); ap.add_argument("--json"); ap.add_argument("--override", action="append", default=[])
    ap.add_argument("--inputs-json"); ap.add_argument("--no-compare", action="store_true")
    args = ap.parse_args()
    inp = Inputs(args.xlsx)
    for o in args.override: inp.override(o)
    fp, payload = inp.fingerprint()
    model = Model(inp); out = model.run()
    print(f"Engine v{ENGINE_VERSION} | {args.xlsx} | inputs sha256 {fp[:16]}… | regime {out['regime']} | overrides {args.override}")
    print(f"FV Bear {out['Bear']['fv']:.4f} | Base {out['Base']['fv']:.4f} | Bull {out['Bull']['fv']:.4f} | weighted {out['weighted_fv']:.4f} | price {out['price']:.2f} | up/down {out['upside']:+.1%}")
    print("Weighted FV by regime:", {k: round(v, 4) for k, v in out["weighted_by_regime"].items()})
    print("Base hashprice path:", {y: round(v, 2) for y, v in out["Base"]["hashprice_path"].items()})
    bad = 0
    if not args.no_compare and not args.override:
        res, bad = compare(out, inp)
        print(f"\n{'Check':44s} {'Engine':>14s} {'Workbook':>14s} {'Diff':>11s}  Status")
        for name, p, wv, d, st in res:
            print(f"{name:44s} {p:14.6f} {(wv if wv is not None else float('nan')):14.6f} {(d if d is not None else float('nan')):11.2e}  {st}")
        print(f"\nCompared {len(res)} outputs — mismatches: {bad}")
    if args.json:
        json.dump(dict(engine=ENGINE_VERSION, inputs_sha256=fp, results=out, mismatches=bad), open(args.json, "w"), indent=2, default=str, ensure_ascii=False)
    if args.inputs_json:
        json.dump(dict(model=args.xlsx, inputs_sha256=fp, assumptions=payload), open(args.inputs_json, "w"), indent=2, ensure_ascii=False)
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()
