# -*- coding: utf-8 -*-
"""Shared definitions for the Mining NAV Standard v1.0: data loading, derived adjustments, parameters."""
import json, glob, os, hashlib, datetime as dt

DATA_DIR = os.environ.get("NAV_DATA_DIR") or (os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data") if os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")) else "/home/claude/nav/data")
VERSION = "1.1"
# Transaction-based ASIC price curve (v1.1): deal panel path + method parameters (see asic_deals.py)
DEALS_PATH = os.environ.get("NAV_DEALS") or os.path.join(DATA_DIR, "asic_deals", "asic_deals_panel_2026-10-17.csv")  # relative to data dir
DEAL_PARAMS = {"window_days": 730, "half_life_months": 9.0, "ref_jth": 16.0, "min_n": 8, "min_distinct_jth": 3, "extrap_lo": 1.0, "extrap_hi": 2.0, "max_extrap_months": 12.0, "local_band": 2.0, "min_local": 3}
DATA_CUT = "2026-10-15"
BTC_SPOT = 82308.83          # USD, 2026-10-15 20:00 UTC (CoinGecko market_chart)
BTC_SPOT_SRC = "CoinGecko API, bitcoin market_chart/range, hourly point 2026-10-15 20:00:00 UTC (= US equity close)"
USDCAD_1015 = 1.4196         # Bank of Canada daily average 2026-10-15
ORDER = ["MARA", "RIOT", "CLSK", "CORZ", "CIFR", "HUT", "ABTC", "WULF", "IREN", "HIVE", "BTDR", "FUFU", "CANG", "KEEL", "ARBK", "SLNH", "LMFA", "DGXX", "DMGI", "BTCT", "VIP"]

# Standard parameters (editable in the workbook's Standard sheet; the engine reads the same values)
PARAMS = {
    "btc_spot": BTC_SPOT,
    "haircut_pledged_btc": 0.10,
    "infra_usd_m_per_mw": 0.35,
    "liq_haircut_other_current": 0.50,
    "liq_haircut_other_noncurrent": 0.50,
    "liq_haircut_ppe": 0.40,
    "liq_haircut_rou": 1.00,
    "liq_winddown_pct_assets": 0.02,
    "stale_bs_days": 120,
    "stale_btc_days": 45,
}
# Reference ASIC price curve (USD per TH/s as a function of fleet efficiency, J/TH). Piecewise linear, flat beyond ends.
ASIC_CURVE = [  # (J/TH, $/TH, note)
    (13.0, 10.20, "Antminer S21 EXP Hyd 3U listing $10.20/TH"),
    (13.5, 12.70, "Antminer S21 XP listing $12.70/TH"),
    (15.0, 9.00, "S21+ Pro $9.91 / S21+ Hyd $8.06 average"),
    (17.0, 7.90, "S21e Hyd $5.46 / WhatsMiner M60S+ $10.35 average"),
    (19.0, 6.00, "interpolated"),
    (21.5, 4.90, "S19k Pro class $4.86/TH (S19 XP listing $21.53 treated as outlier)"),
    (25.0, 3.50, "interpolated"),
    (29.5, 2.00, "Antminer S19j Pro $200 per 100 TH"),
    (34.0, 1.00, "legacy S19 class"),
    (40.0, 0.50, "end-of-life"),
]
ASIC_CURVE_SRC = ("Endless Mining ASIC Miner Price Index, model table as of 2026-10-16 (lowest live asking prices; headline index median $10.31/TH for week 2026-10-05..11). "
                  "v1.1: COMPARISON ONLY — NAV-M uses the transaction-based hedonic curve (sheet ASIC_Curve, asic_deals.py).")

FIELDS = [  # (field key, sheet label, unit, json path)
    ("cash", "Cash and equivalents", "$m", ("bs", "cash")),
    ("restricted_cash", "Restricted cash", "$m", ("bs", "restricted_cash")),
    ("btc_count_bs", "BTC count at balance sheet date", "BTC", ("bs", "btc_count_bs")),
    ("btc_carrying_value", "BTC carrying value (incl. receivables)", "$m", ("bs", "btc_carrying_value")),
    ("other_digital_assets_value", "Other digital assets (book)", "$m", ("bs", "other_digital_assets_value")),
    ("btc_pledged", "BTC pledged / loaned / receivable", "BTC", ("bs", "btc_pledged_or_loaned_count")),
    ("equipment_deposits", "Equipment deposits", "$m", ("bs", "equipment_deposits")),
    ("other_current_assets", "Other current assets", "$m", ("bs", "other_current_assets")),
    ("ppe_net_total", "PPE net, total", "$m", ("bs", "ppe_net_total")),
    ("ppe_mining_equipment_net", "PPE: mining equipment net", "$m", ("bs", "ppe_mining_equipment_net")),
    ("ppe_infra_net", "PPE: land / buildings / infrastructure net", "$m", ("bs", "ppe_land_buildings_infra_net")),
    ("cip", "Construction in progress", "$m", ("bs", "construction_in_progress")),
    ("rou_assets", "Right-of-use assets", "$m", ("bs", "rou_assets")),
    ("goodwill_intangibles", "Goodwill and intangibles", "$m", ("bs", "goodwill_intangibles")),
    ("investments_other_noncurrent", "Investments and other non-current assets", "$m", ("bs", "investments_other_noncurrent")),
    ("total_assets", "Total assets", "$m", ("bs", "total_assets")),
    ("ap_accrued", "Accounts payable and accrued", "$m", ("bs", "accounts_payable_accrued")),
    ("deferred_revenue", "Deferred revenue / customer deposits", "$m", ("bs", "deferred_revenue_customer_deposits")),
    ("lease_liabilities", "Lease liabilities", "$m", ("bs", "lease_liabilities")),
    ("other_liabilities", "Other liabilities", "$m", ("bs", "other_liabilities")),
    ("total_liabilities", "Total liabilities", "$m", ("bs", "total_liabilities")),
    ("total_equity", "Total equity (book)", "$m", ("bs", "total_equity")),
    ("nci", "Non-controlling interest", "$m", ("bs", "noncontrolling_interest")),
    ("preferred", "Preferred liquidation preference", "$m", ("bs", "preferred_liquidation_preference")),
    ("debt_principal", "Debt principal (balance-sheet instruments)", "$m", None),
    ("debt_carrying", "Debt carrying value (balance-sheet instruments)", "$m", None),
    ("basic_shares", "Basic shares outstanding", "m", ("shares", "basic_outstanding")),
    ("rsu", "Unvested RSU/PSU not in basic count", "m", ("shares", "rsu_unvested")),
    ("btc_latest", "BTC held, latest disclosed", "BTC", ("ops", "btc_held_latest")),
    ("hashrate_op", "Hashrate operating", "EH/s", ("ops", "hashrate_ehs_operating")),
    ("hashrate_inst", "Hashrate installed / owned fleet", "EH/s", ("ops", "hashrate_ehs_installed")),
    ("jth", "Fleet efficiency", "J/TH", ("ops", "fleet_efficiency_jth")),
    ("mw_owned", "Energized MW owned", "MW", ("ops", "energized_mw_owned")),
    ("mw_hosted", "Energized MW hosted (third party)", "MW", ("ops", "energized_mw_hosted_third_party")),
    ("mw_total", "Total contracted power", "MW", ("ops", "total_contracted_power_mw")),
    ("price", "Share price 2026-10-15 close", "$", ("market", "price_close_2026_10_15_usd")),
]
DATE_FIELDS = [("balance_sheet_date", "Balance sheet date"), ("basic_date", "Share count date"), ("btc_held_date", "BTC count date"), ("hashrate_date", "Hashrate date")]

# ------------------------------------------------------------------ derived per-company adjustments (documented; every line sourced in the company JSON notes)
ADJ_FIELDS = [
    ("btc_used", "BTC count used (latest disclosed or BS)", "BTC"),
    ("btc_pledged_used", "BTC pledged used", "BTC"),
    ("btc_owed", "BTC owed under BTC-denominated loans", "BTC"),
    ("btc_loan_book", "Book value of BTC loan inside debt principal (replaced by BTC owed x spot)", "$m"),
    ("warrant_liability", "Share-settled warrant liability inside total liabilities (removed; shares added)", "$m"),
    ("penny_warrants", "Penny / pre-funded warrants (added to shares)", "m"),
    ("itm_tsm_shares", "In-the-money options/warrants, treasury-stock shares", "m"),
    ("itm_conv_principal", "In-the-money convertibles, principal", "$m"),
    ("itm_conv_shares", "In-the-money convertibles, shares on conversion", "m"),
    ("mezzanine_claims", "Mezzanine / redeemable NCI claims ahead of common", "$m"),
    ("debt_carrying_override", "Debt carrying total per filing (override when per-instrument carrying is n/d)", "$m"),
    ("debt_like", "Debt-like obligations added to EV (already inside NAV liabilities)", "$m"),
    ("pf_cash", "Pro forma cash delta (disclosed post-BS events)", "$m"),
    ("pf_debt", "Pro forma debt principal delta", "$m"),
    ("pf_shares", "Pro forma share delta", "m"),
    ("ppe_basis", "PPE basis for NAV-M (MARK / BOOK)", "code"),
    ("flags", "Data flags", "text"),
]
ADJ = {
    "MARA": dict(btc_used=35577, btc_pledged_used=9270, mezzanine_claims=82.461, pf_cash=600.0, pf_debt=600.0, ppe_basis="BOOK",
                 flags="Aug-2026 BTC-backed loans +$600m assumed held as cash (use undisclosed); PPE net split and owned MW n/d; convert carrying n/d (principal used)"),
    "RIOT": dict(btc_used=11380, btc_pledged_used=5821, itm_conv_principal=594.4, itm_conv_shares=39.988, debt_carrying_override=843.027, pf_cash=-200.0, pf_debt=-200.0, ppe_basis="MARK",
                 flags="Coinbase $200m prepaid 2026-09-21 (5,821 BTC released, still shown pledged); 2030 notes marginally ITM (derived cp $14.86); PPE includes HPC build (Corsicana) - NAV-M at mining-grade $/MW understates"),
    "CLSK": dict(btc_used=13530, btc_pledged_used=3475, itm_tsm_shares=1.768, pf_cash=2219.1, pf_debt=2276.0, ppe_basis="MARK",
                 flags="Sandersville notes 25.09.2026 pro forma; BTC count 30.09 vs cash 30.06 (sale proceeds not added); options/warrants TSM 50% assumption"),
    "CORZ": dict(btc_used=848, btc_pledged_used=0, warrant_liability=1975.27, penny_warrants=6.6, itm_tsm_shares=50.998, itm_conv_principal=460.0, itm_conv_shares=41.818, debt_carrying_override=4297.967, ppe_basis="BOOK",
                 flags="HPC colocation company; mining in run-off (no hashrate disclosed); $6.81 warrants TSM at $14.46; Polaris acquisition (Aug) not pro forma'd (cash->PPE)"),
    "CIFR": dict(btc_used=646, btc_pledged_used=53, warrant_liability=632.06, penny_warrants=24.179, itm_conv_principal=6.6, itm_conv_shares=1.483, debt_carrying_override=5541.35, pf_cash=850.0, pf_debt=684.1, pf_shares=40.7, ppe_basis="BOOK",
                 flags="Pro forma: +$850m 0% converts 2032 (gross, fees n/d), exchange of $165.9m 2030 notes into 40.7m shares; remaining 2030 notes ITM; no hashrate disclosed"),
    "HUT": dict(btc_used=17316, btc_pledged_used=7940, itm_tsm_shares=1.886, debt_carrying_override=7638.4, debt_like=371.687, ppe_basis="BOOK",
                 flags="Consolidates ABTC (53.63% economic; NCI at book); $7.5bn project notes non-recourse with proceeds in restricted cash; hashrate = ABTC fleet"),
    "ABTC": dict(btc_used=8002, btc_pledged_used=3090, debt_like=371.687, ppe_basis="MARK",
                 flags="All 8,002 BTC counted and $371.7m miner purchase liability (Bitmain redemption price) deducted at book; fully hosted at Hut 8 (MW owned 0)"),
    "WULF": dict(btc_used=2, btc_pledged_used=0, warrant_liability=1816.69, penny_warrants=73.58, itm_tsm_shares=3.588, itm_conv_principal=1500.0, itm_conv_shares=139.42, debt_carrying_override=5213.1, ppe_basis="BOOK",
                 flags="Google penny warrants 73.58m added to shares; 2030 ($8.48) and 2031 ($12.43) converts ITM at $12.62; Abernathy JV sale ($530m vs $424m carrying) not pro forma'd; mining residual"),
    "IREN": dict(btc_used=0, btc_pledged_used=0, itm_conv_principal=445.699, itm_conv_shares=29.74, debt_carrying_override=7592.9, pf_shares=10.555, ppe_basis="BOOK",
                 flags="AI cloud company; no BTC held; 2029/2030 converts ITM (capped calls offset part of dilution, not modelled); shares pro forma to proxy count 404.6m (28.09.2026); $2.4bn Aug-2026 GPU financing drawn amount n/d"),
    "HIVE": dict(btc_used=190, btc_pledged_used=0, warrant_liability=2.154, pf_cash=6.3, ppe_basis="MARK",
                 flags="212 BTC held by equipment vendor as deposits excluded; Swedish VAT provision $84.7m in liabilities; PPE includes GPU fleet (not marked); ATM +$6.3m gross post-quarter"),
    "BTDR": dict(btc_used=406, btc_pledged_used=0, btc_owed=1953.84, btc_loan_book=117.548, itm_tsm_shares=4.343, pf_cash=58.0, pf_shares=4.367, ppe_basis="MARK",
                 flags="Net BTC position negative: BTC-denominated loan 1,953.84 BTC at 30.06 (3,669 at 29.09, not pro forma'd) deducted at spot; USDT receivable $162m in other current assets; 1,752 MW includes AI-conversion sites; Barclays zero-strike calls (24.5m shares) not netted"),
    "FUFU": dict(btc_used=1388, btc_pledged_used=54, ppe_basis="MARK",
                 flags="Asset-light: 3.8 EH/s self-owned of 19.4 under management; Bitmain deferred payable $93.4m treated as debt; Ethiopia 80 MW assets at risk"),
    "CANG": dict(btc_used=1056, btc_pledged_used=873, itm_tsm_shares=1.292, ppe_basis="BOOK",
                 flags="Pledged BTC derived from carrying split (receivable for bitcoin collateral $61.5m of $74.4m); income tax payable $88.4m in liabilities; J/TH n/d so NAV-M not applied; condensed balance sheet without notes"),
    "KEEL": dict(btc_used=1861, btc_pledged_used=0, itm_tsm_shares=3.573, debt_carrying_override=1025.829, ppe_basis="BOOK",
                 flags="Exit from mining announced; EH/s no longer disclosed; options WAEP C$2.94 treated ITM at $2.57; capped-call derivative asset $78.8m kept at book"),
    "ARBK": dict(btc_used=0, btc_pledged_used=0, pf_debt=-1.16, ppe_basis="BOOK",
                 flags="STALE: latest balance sheet 2025-12-31 (20-F); BTC count n/d (carrying used); price per ordinary share = ADS $1.92 / 2,160; Growler advances converted to equity 2026-03 (shares n/d)"),
    "SLNH": dict(btc_used=0, btc_pledged_used=0, debt_carrying_override=33.119, pf_cash=4.5, pf_debt=-15.2, pf_shares=18.769, ppe_basis="BOOK",
                 flags="Preferred $158.1m (incl. arrears) and NCI $54.5m rank ahead; pro forma: Generate A-1/A-3 prepaid ($15.2m + $3.9m premium) and ATM +$23.6m / 18.77m shares; no EH/s disclosed"),
    "LMFA": dict(btc_used=63.7, btc_pledged_used=0, pf_debt=-18.345, pf_shares=0.741, ppe_basis="BOOK",
                 flags="Pro forma 30.09.2026: 63.7 BTC, $1.25m debt, 2.535m shares after Arch collar loan settled by BTC sale; cash at 30.06; going-concern language; now PowerCompute (PWCM)"),
    "DGXX": dict(btc_used=217, btc_pledged_used=0, warrant_liability=4.25, ppe_basis="BOOK",
                 flags="Debt-free; residual mining (3 BTC mined in Q2); GPU assets leased out; warrants $2.00-3.66 partly ITM at $2.79 (immaterial, ignored)"),
    "DMGI": dict(btc_used=379.2, btc_pledged_used=346.45, ppe_basis="MARK",
                 flags="CAD statements converted at BoC 1.4210 (30.06) and 1.4196 (15.10); 91% of BTC pledged to Sygnum demand loan; 49 BTC + 45 ETH stuck at Prime Trust included in count; monthly updates discontinued"),
    "BTCT": dict(btc_used=0, btc_pledged_used=0, penny_warrants=0.965, pf_cash=7.007, pf_debt=0.767, ppe_basis="BOOK",
                 flags="STALE: latest balance sheet 2025-12-31; BTC/ETH unit counts n/d (carrying used); pro forma June-2026 PIPE cash (+$6.24m) and officer loans (+$0.77m); shares 16.98m at 24.07.2026"),
    "VIP": dict(btc_used=103, btc_pledged_used=0, pf_cash=8.5, pf_debt=-20.308, ppe_basis="BOOK",
                 flags="Pro forma: PIPE $39.4m (10.09), 2026 notes redeemed $30.9m (13.10), MIG $10m convertible; environmental $31.0m and RGGI $15.2m liabilities; MW owned n/d (106 MW gas plant)"),
}
for t in ORDER:
    for k, _, _ in ADJ_FIELDS:
        ADJ[t].setdefault(k, "" if k in ("ppe_basis", "flags") else 0)


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


def load_companies():
    out = {}
    for t in ORDER:
        d = json.load(open(os.path.join(DATA_DIR, f"{t}.json"), encoding="utf-8"))
        out[t] = d
    return out


def debt_totals(d):
    """Balance-sheet instruments only: exclude memo / post-balance-sheet / cancelled entries."""
    p = c = 0.0
    for e in d["debt"]:
        name = str(e.get("instrument", ""))
        if name.startswith("[") or name.upper().startswith("MEMO") or "NOT IN TOTAL" in name.upper() or "EXCLUDED" in name.upper(): continue
        pr = e.get("principal"); ca = e.get("carrying")
        pr = float(pr) if pr not in (None, "") else 0.0
        ca = float(ca) if ca not in (None, "") else pr
        p += pr; c += ca
    return p, c


def flat_rows(companies):
    """Long-format rows: (ticker, field, label, unit, value, src, note)."""
    rows = []
    for t in [x for x in ORDER if x in companies]:
        d = companies[t]
        for key, label, unit, path in FIELDS:
            if path is None:
                p, c = debt_totals(d)
                v = p if key == "debt_principal" else c
                rows.append((t, key, label, unit, v, "debt[]", "sum of balance-sheet instruments (memo/post-BS/cancelled entries excluded)")); continue
            o = d[path[0]].get(path[1]) if path[0] in d else None
            if isinstance(o, dict):
                v = num(o); src = o.get("src", ""); note = o.get("note", "")
            else:
                v = num(o); src = ""; note = ""
            if key in ("basic_shares", "rsu") and v is not None: v = v / 1e6
            if key == "basic_shares" and t == "ARBK" and v is not None:
                v = v / 2160.0; note = "ADS-equivalents = ordinary shares / 2,160 (price is per ADS); " + note
            rows.append((t, key, label, unit, v, src, note))
        for key, label in DATE_FIELDS:
            v = d.get(key) or d.get("shares", {}).get(key) or d.get("ops", {}).get(key) or ""
            rows.append((t, key, label, "date", v, "", ""))
    return rows


def asic_price_per_th(jth, curve=ASIC_CURVE):
    pts = sorted((x, y) for x, y, _ in curve)
    if jth is None: return None
    if jth <= pts[0][0]: return pts[0][1]
    if jth >= pts[-1][0]: return pts[-1][1]
    for (x0, y0), (x1, y1) in zip(pts, pts[1:]):
        if x0 <= jth <= x1: return y0 + (y1 - y0) * (jth - x0) / (x1 - x0)


def load_deals():
    import asic_deals as AD
    rows, mp = AD.load_panel(DEALS_PATH)
    return rows


def fingerprint(companies, deals=None):
    payload = {t: {"bs": companies[t]["bs"], "debt": companies[t]["debt"], "shares": companies[t]["shares"], "ops": companies[t]["ops"], "market": companies[t]["market"],
                   "balance_sheet_date": companies[t]["balance_sheet_date"]} for t in ORDER}
    s = json.dumps({"version": VERSION, "params": PARAMS, "deal_params": DEAL_PARAMS, "ask_curve": ASIC_CURVE, "adj": ADJ, "data": payload, "deals": deals}, sort_keys=True, ensure_ascii=False, default=str)
    return hashlib.sha256(s.encode("utf-8")).hexdigest()
