"""
HASHFLOPS Mining Capacity Standard v1.0 — shared data set, parameters and pure-Python metric engine.

Data cut 2026-10-15 (shared with Mining NAV Standard v1.1 and Mining Cost Standard v1.0):
  - price: Nasdaq close 2026-10-15 (stockanalysis.com history, per NAV v1.1 data set)
  - BTC spot: 82,308.83 USD (CoinGecko BTC/USD 2026-10-15 20:00 UTC)
  - balance sheet: latest filed 10-Q / 10-K / 6-K (period end 2026-06-30) + disclosed subsequent events (PF)
  - capacity: company disclosures through 2026-10-15 (10-Q MD&A, 8-K/6-K releases, investor decks)

All money in USD millions. MW are gross utility (grid) megawatts unless basis says otherwise.
"""
import json, hashlib

VERSION = "1.0"
DATA_CUT = "2026-10-15"
RELEASE = "2026-10-17"

PARAMS = {
    "btc_spot_usd": 82308.83,
    "btc_spot_source": "CoinGecko BTC/USD 2026-10-15 20:00 UTC (same data cut as Mining NAV Standard v1.1)",
    "it_to_gross_default": 1.30,          # used only where a company discloses IT MW but no gross figure and no own ratio
    "committed_horizon_months": 24,
    "committed_cutoff": "2028-10-15",
    "stale_bs_days": 120,
    "stale_price_days": 5,
    "medians_min_n": 5,
}

# cohort: A = BTC-mining weighted (mining revenue > HPC revenue in H1 2026, no multi-GW HPC build),
#         B = HPC/AI-pivot (HPC leasing/AI cloud revenue or contracted HPC MW exceed mining)
COMPANIES = [
 dict(ticker="BTDR", company="Bitdeer Technologies Group", cohort="A",
      price=8.40, shares_m=271.782245, pf_shares_m=4.367199,
      debt_face=1875.0, pf_debt=0.0, cash=456.838, restricted=39.450, pf_cash=58.0, nci=0.0,
      btc=406, btc_pledged=0, nonrecourse=0.0,
      d1=1752.0, d1_basis="G", d2=2110.2, d3=2980.2, hashrate_ehs=73.0,
      bs_date="2026-06-30", filing="6-K (Q2 2026 results 2026-08-10; H1 2026 FS 2026-09-29)", filed="2026-09-29",
      conf="B",
      mw_note=("D1 = company 'Online Electrical Capacity' 1,752 MW at 2026-07-31 (Rockdale 563, Knoxville 86, Wenatchee 13, Molde 84, "
               "Tydal 180, Gedu 100, Jigmeling 500, Oromia 50, Massillon 174, Cyberjaya 2) — includes AI-conversion sites whose data halls "
               "are not yet in service. D2 = D1 + Massillon 47 + Rockdale 179 (2026) + Fox Creek 101 (Q4'27) + Cyberjaya 9.5 + Johor Bahru 21.7 (Q1'27); "
               "Clarington 570 excluded (timing 'to be updated', litigation) and Weathersfield 300 (Q4'28) outside the 24-month window. "
               "D3 = company 'Total Global Electrical Capacity' 2,980.2 MW."),
      fin_note=("Face debt $1,875m (convertible notes + BIT Group asset-collateralized loan + bank loans; BTC-denominated related-party loan at book). "
                "PF: +4.367m Class A shares issued 2026-07-01..09-29 for net $58.0m (6-K 2026-09-29). BTC held 406 at 2026-06-30; a 1,953.84 BTC "
                "loan is owed to a related party (inside borrowings). Mining-weighted: 73.0 EH/s self-mining; Tydal 121 IT MW leased to Volta (16-yr, ~$4.7bn).")),
 dict(ticker="MARA", company="MARA Holdings, Inc.", cohort="A",
      price=8.33, shares_m=386.299297, pf_shares_m=0.0,
      debt_face=2447.201, pf_debt=600.0, cash=421.274, restricted=12.0, pf_cash=600.0, nci=98.846,
      btc=35577, btc_pledged=9270, nonrecourse=0.0,
      d1=1900.0, d1_basis="G", d2=2405.0, d3=4800.0, hashrate_ehs=70.3,
      bs_date="2026-06-30", filing="10-Q Q2 2026", filed="2026-08-06", conf="B",
      mw_note=("D1 = 'Total energy capacity' 1.9 GW at 2026-06-30 (10-Q MD&A) — includes third-party-hosted capacity; owned/hosted split not disclosed. "
               "D2 = D1 + Long Ridge 505 MW nameplate (485 MW CCGT; equity purchase agreement 2026-04-29, pending FERC, management guides close by year-end 2026). "
               "D3 = company 'potential power portfolio ~4.8 GW' (Long Ridge campus >1 GW + Matagorda County TX 2,000 MW site, ERCOT approval pending)."),
      fin_note=("Face debt $2,447.2m at 2026-06-30 (five convertible series $2,297.2m + Coinbase BTC-backed line $150m). PF: +$600m incremental BTC-backed term loans "
                "(Coinbase $300m floating, Two Prime $300m 7.65%, 2026-08-04) added to debt and to cash (use of proceeds: Long Ridge; held as cash until close). "
                "NCI: permanent $16.4m + redeemable (Exaion put) $82.5m. BTC 35,577 (9,270 loaned/pledged; 18,750 pledged post-quarter).")),
 dict(ticker="CLSK", company="CleanSpark, Inc.", cohort="A",
      price=8.92, shares_m=256.817073, pf_shares_m=0.0,
      debt_face=1811.559, pf_debt=2276.0, cash=202.601, restricted=3.738, pf_cash=2219.1, nci=0.0,
      btc=13530, btc_pledged=3475, nonrecourse=2276.0,
      d1=808.0, d1_basis="U", d2=1800.0, d3=1800.0, hashrate_ehs=50.0,
      bs_date="2026-06-30", filing="10-Q fiscal Q3 2026 + 8-K 2026-09-25 + Sept-2026 operational update", filed="2026-10-09", conf="B",
      mw_note=("D1 = 'Utilized MW' 808 (maximum concurrent MW used by the fleet, September 2026 operational update, 2026-10-09). Basis U: utilized load, not "
               "energized nameplate — the last nameplate disclosure was 1,027 MW operational capacity at 2025-09-30 (FY2025 10-K); the company now reports only "
               "utilized MW and GW under contract. D2 = 1.8 GW under contract (all contracted power for owned/leased sites incl. Texas 585 MW ERCOT batch-zero "
               "baseload + 300 MW studied-load designations received Sept 2026; energization guided 2027, subject to the Texas data-center audit). "
               "D3 = D2: no development pipeline disclosed beyond contracted power (the 885 MW Texas exclusivity granted to the Sandersville tenant is inside the 1.8 GW)."),
      fin_note=("Face debt $1,811.6m at 2026-06-30 (0% converts 2030 $650m + 2032 $1,150m + other $11.6m). PF: +$2,276.0m CSDC Finance I 7.875% senior secured notes "
                "due 2031 (Sandersville project, non-recourse, issued 2026-09-25 at 98.5) with est. net proceeds $2,219.1m added to cash (incl. $327m DSRA). "
                "BTC 13,530 at 2026-09-30 (3,475 posted as collateral/receivable). Sandersville: 175 IT MW / ~250 MW gross 20-yr NNN lease, $6.56bn base rent, RFS Q4 2027.")),
 dict(ticker="IREN", company="IREN Limited", cohort="B",
      price=30.39, shares_m=404.613536, pf_shares_m=0.0,
      debt_face=7705.6, pf_debt=0.0, cash=5895.6, restricted=1724.0, pf_cash=0.0, nci=0.0,
      btc=0, btc_pledged=0, nonrecourse=938.0,
      d1=2310.0, d1_basis="G", d2=2910.0, d3=5000.0, hashrate_ehs=23.2,
      bs_date="2026-06-30", filing="10-K FY2026 (fiscal year ended 2026-06-30)", filed="2026-08-27", conf="B",
      mw_note=("D1 = grid-connected, energized site capacity per the 10-K Item 1 site table: Childress TX 750 + Sweetwater 1 1,400 (substation energized April 2026) + "
               "Canal Flats 30 + Prince George 50 + Mackenzie 80 = 2,310 MW. Load in service is far lower (~380 MW mining being decommissioned + AI Cloud; company "
               "targets 480 MW gross AI Cloud capacity in 2026 and 1.2 GW gross in 2027) — flagged as utilization gap. D2 = D1 + Sweetwater 2 600 MW (2028; the 2 GW "
               "Sweetwater hub was included as base load in ERCOT Batch Zero on 2026-09-08). D3 = company '~5 GW of total power capacity' under grid connection "
               "agreements/letters of agreement (adds Kiowa OK, Bundey AU, Badajoz ES)."),
      fin_note=("Face debt $7,705.6m at 2026-06-30 (six convertible series $6,745.7m + other $22.0m + non-recourse GPU financing drawn $938.0m of $3,645m). "
                "Cash $5,895.6m + restricted $1,724.0m. Deferred revenue $1.84bn (customer prepayments) is not debt. Shares 404,613,536 at 2026-09-28 (DEF 14A; "
                "incl. 12.6m Mirantis shares) replaces the 10-K cover count 394,058,648. No BTC held (sold daily). Aug-2026 $2.4bn Mackenzie GPU financing: drawn amount n/d, not PF.")),
 dict(ticker="RIOT", company="Riot Platforms, Inc.", cohort="A",
      price=15.50, shares_m=375.258935, pf_shares_m=0.0,
      debt_face=853.681, pf_debt=-200.0, cash=471.383, restricted=77.485, pf_cash=-200.0, nci=0.0,
      btc=11380, btc_pledged=5821, nonrecourse=0.0,
      d1=1292.0, d1_basis="G", d2=1892.0, d3=1892.0, hashrate_ehs=44.4,
      bs_date="2026-06-30", filing="10-Q Q2 2026 + 8-K 2026-09-25", filed="2026-09-25", conf="A",
      mw_note=("D1 = 'Developed power capacity' at 2026-06-30: Rockdale 700 + Corsicana 400 + Kentucky 192 = 1,292 MW (10-Q MD&A), all owned sites; part of Rockdale "
               "serves the AMD and frontier-AI-lab data-center leases (241 IT MW contracted). D2 = D1 + Corsicana expansion to ~1 GW developed (+600 MW; substation "
               "interconnect in place, build 2027-2028; whole campus under non-binding LOI to a single tenant). D3 = D2: no further pipeline disclosed."),
      fin_note=("Face debt $853.7m at 2026-06-30 (0.75% converts 2030 $594.4m, Coinbase BTC-backed $200m, revolvers $54.3m, note $5.0m). PF: Coinbase facility fully "
                "prepaid and terminated 2026-09-21 (-$200m debt, -$200m cash; 5,821 pledged BTC released). $573m Morgan Stanley interim project facility (Aug 2026, "
                "non-recourse) excluded: drawn amount not disclosed. BTC 11,380 at 2026-06-30 (no later update published).")),
 dict(ticker="CORZ", company="Core Scientific, Inc.", cohort="B",
      price=14.46, shares_m=321.340441, pf_shares_m=0.0,
      debt_face=4385.0, pf_debt=0.0, cash=1769.735, restricted=781.656, pf_cash=0.0, nci=0.0,
      btc=848, btc_pledged=0, nonrecourse=3300.0,
      d1=568.1, d1_basis="IT->G", d2=1430.0, d3=4504.5, hashrate_ehs=None,
      bs_date="2026-06-30", filing="10-Q Q2 2026 + Q2 earnings deck", filed="2026-07-28", conf="C",
      mw_note=("Core Scientific discloses colocation capacity in critical-IT MW only (Billable 437 MW mid-July 2026; Leased ~1,100 MW; Total Leasable ~1,540 MW; AMD "
               "reservation right up to 1,925 MW more) and no gross utility figure in the Q2 10-Q. All three denominators are converted IT->gross at the Standard default "
               "1.30 (Assumption): D1 = 437 x 1.30 = 568 (energized-but-unbilled HPC capacity and residual self-mining load are not quantified by the company and are "
               "excluded); D2 = 1,100 x 1.30 = 1,430 (CoreWeave ~590 MW by early 2027; AMD/Neocloud ~530 MW 2027-2028); D3 = (1,540 + 1,925) x 1.30 = 4,505. "
               "Hunt County (~430 MW gross) and Polaris/Muskogee (up to 440 MW gross) acquisitions sit inside the leasable/reservation figures."),
      fin_note=("Face debt $4,385m at 2026-06-30 (7.75% senior secured notes 2031 $3,300m at Core Scientific Finance — CoreWeave-site SPV, non-recourse; 3% converts "
                "2029 $460m; 0% converts 2031 $625m); $1.0bn term loan repaid May 2026. Cash $1,769.7m + restricted $781.7m (incl. $344.8m DSRA). Warrant liabilities "
                "$1,975m (share-settled, 103m warrants) excluded from debt. Post-quarter Polaris acquisition (~$421m cash, 2026-08-13) not PF. BTC 848. Mining in run-off; no hashrate disclosed.")),
 dict(ticker="CIFR", company="Cipher Digital Inc. (ex-Cipher Mining)", cohort="B",
      price=10.04, shares_m=415.030722, pf_shares_m=40.7,
      debt_face=6015.5, pf_debt=684.1, cash=831.829, restricted=3727.958, pf_cash=850.0, nci=25.679,
      btc=646, btc_pledged=53, nonrecourse=4543.0,
      d1=507.0, d1_basis="G", d2=907.0, d3=5300.0, hashrate_ehs=None,
      bs_date="2026-06-30", filing="10-Q Q2 2026 + 8-K 2026-10-14 (converts) + investor deck 2026-10-13", filed="2026-10-14", conf="B",
      mw_note=("D1 = Odessa 207 MW (wholly owned mining site, Luminant PPA) + Black Pearl 300 MW gross (Wink TX; energized N+1 substation, 216 IT MW AWS lease, first "
               "capacity delivered and rent commenced Aug 2026) = 507 MW. D2 = company 'operating + contracted' 907 MW at 2026-09-30 (= 207 mining + 700 MW gross "
               "contracted HPC: Black Pearl 300, Barber Lake 300 (Fluidstack/Google, 20-yr after Sept-2026 amendment, delivery Q4'26-Q1'27), Stingray (H1 2027)). "
               "D3 = 'approximately 5.3 GW of capacity across 11 sites, at various stages of interconnection' (10-Q MD&A; Oct-2026 deck: 907 MW + ~3.4 GW near-term "
               "pipeline energizing 2027-2030, plus Apollo 900 MW option and Colchis 1 GW)."),
      fin_note=("Face debt $6,015.5m at 2026-06-30 (project notes: Cipher Compute 7.125% $1,733m, Black Pearl Compute 6.125% $2,000m, Stingray Compute 6.0% $810m — "
                "all non-recourse to the parent; converts 1.75% 2030 $172.5m, 0% 2031 $1,300m). PF (priced 2026-10-14, settled 2026-10-16): +$850m 0% converts 2032 "
                "(cash +$850m gross) and exchange of $165.9m 2030 notes into 40.7m shares (debt -$165.9m) -> net debt +$684.1m, shares +40.7m. Restricted cash $3,728m = "
                "undisbursed project-note proceeds. Warrant liability $632m (24.2m Google penny warrants) excluded from debt; redeemable NCI (Colchis 24%) $25.7m added.")),
 dict(ticker="HIVE", company="HIVE Digital Technologies Ltd.", cohort="A",
      price=2.22, shares_m=267.43, pf_shares_m=0.0,
      debt_face=275.979, pf_debt=0.0, cash=208.039, restricted=0.0, pf_cash=6.3, nci=0.0,
      btc=190, btc_pledged=0, nonrecourse=0.0,
      d1=440.0, d1_basis="G", d2=610.0, d3=930.0, hashrate_ehs=25.2,
      bs_date="2026-06-30", filing="10-Q fiscal Q1 2027 (quarter ended 2026-06-30)", filed="2026-08-14", conf="B",
      mw_note=("D1 = 'approximately 440 MW of global power capacity' operated across Canada, Sweden and Paraguay (fiscal Q1 2027 release, 2026-08-15; site table at "
               "2026-07-31 shows 457.5 MW capacity available / 389.5 MW utilized at owned + leased sites). D2 = D1 + 100 MW Yguazu PPA (energization Q4 2026) + 70 MW "
               "Tier-III builds (New Brunswick, Toronto, Little Boden; 2027) = 610. D3 = D2 + planned 320 MW GTA 'Gigafactory' (2028) = 930."),
      fin_note=("Face debt $276.0m at 2026-06-30 ($115m + $130m 0% exchangeable notes 2031, Boden loan $10.9m, Atlantic term loans $1.6m, vendor mortgages $18.5m); "
                "lease liabilities $108.5m and the $84.7m Swedish VAT provision are not debt. PF: +$6.3m gross ATM proceeds after quarter-end. Share count 267.43m is "
                "from market-data aggregators (2026-07-23/30) — the 10-Q cover count was not captured in the shared data set (WARN). BTC 190 (sells mined BTC).")),
 dict(ticker="WULF", company="TeraWulf Inc.", cohort="B",
      price=12.62, shares_m=498.968677, pf_shares_m=0.0,
      debt_face=5725.0, pf_debt=0.0, cash=2619.191, restricted=409.417, pf_cash=0.0, nci=0.0,
      btc=2, btc_pledged=0, nonrecourse=3200.0,
      d1=500.0, d1_basis="G", d2=982.0, d3=2842.0, hashrate_ehs=10.6,
      bs_date="2026-06-30", filing="10-Q Q2 2026 + 8-K 2026-10-05 (Muskie 1 GW)", filed="2026-10-05", conf="B",
      mw_note=("D1 = Lake Mariner (Barker NY) energized grid capacity 500 MW (company: '500 MW of infrastructure capacity', expansion to 750 MW gross HPC leasing "
               "capacity pursued subject to interconnection approval); in-service load at 2026-07: 145 MW mining (being repurposed) + 102 IT MW HPC revenue-generating "
               "(438 IT MW contracted; 336 IT MW under construction). Company-disclosed gross/IT ratio at Lake Mariner = 750/600 = 1.25. D2 = D1 + Justified Data Campus "
               "(Hawesville KY) 482 MW utility power approved by Kentucky PSC 2026-08-24 (Anthropic 401 IT MW lease, delivery H2 2027 - early 2028) = 982. D3 = Lake Mariner "
               "750 + Justified 482 + Muskie 1,000 (Kentucky Power ESA, 2028-2029) + Chesapeake/Morgantown MD ~210 (FERC-authorized generation site, pending close) + "
               "Cayuga/Lake Hawkeye 400 gross potential (2029) = 2,842."),
      fin_note=("Face debt $5,725.0m at 2026-06-30 (WULF Compute 2030 secured notes $3,200m — project-level with a TeraWulf completion guarantee, treated as non-recourse "
                "to the parent with a flag; converts 2030 $500m, 2031 $1,000m, 2032 $1,025m). Cash $2,619.2m + restricted $409.4m. Warrant liability $1,817m (73.58m Google "
                "penny warrants) excluded from debt. Abernathy JV sale (~$530m, 2026-2027 instalments) not PF. BTC 2.")),
 dict(ticker="HUT", company="Hut 8 Corp. (consolidates American Bitcoin, ABTC)", cohort="B",
      price=76.09, shares_m=123.259468, pf_shares_m=0.0,
      debt_face=7738.407, pf_debt=0.0, cash=233.579, restricted=6787.147, pf_cash=0.0, nci=311.410,
      btc=17316, btc_pledged=7940, nonrecourse=7535.104,
      d1=710.0, d1_basis="G", d2=2040.0, d3=9370.0, hashrate_ehs=28.1,
      bs_date="2026-06-30", filing="10-Q Q2 2026 + Q2 release 2026-08-04 + 8-K 2026-09-24", filed="2026-09-24", conf="B",
      mw_note=("D1 = 'Energy Capacity Under Management' 710 MW at 2026-06-30 (all power-related assets incl. ASIC-compute sites Alpha NY, Medicine Hat AB, Salt Creek TX, "
               "Vega TX, Drumheller AB; 280 MW King Mountain JV managed services; ~3 MW Hut 8 Canada). D2 = D1 + 'Energy Capacity Under Construction' 1,330 MW post-quarter "
               "(River Bend LA 330 MW utility / 245 IT, first data hall Q2 2027; Beacon Point TX 1,000 MW utility / 704 IT across Phase 1 (Q3 2027) and Phase 2 (Q2 2028)) = "
               "2,040. D3 = 'Total Energy Capacity Pipeline' 9,370 MW at 2026-06-30 (Under Diligence 5,400 + Under Exclusivity 1,880 + Under Development 550 + Under "
               "Construction 830 + Under Management 710)."),
      fin_note=("Face debt $7,738.4m at 2026-06-30: River Bend 6.192% notes 2042 $3,250m + Beacon Point 6.129% notes 2042 $4,250m (both investment-grade project notes, "
                "non-recourse to Hut 8 Corp., proceeds in restricted project accounts $6,787m) + FalconX BTC-backed term loan $200m + TZRC note $35.1m (non-recourse) + SAFE "
                "$3.3m. Parent-level recourse debt nil after the Coatue note conversion (May 2026). Consolidated BTC 17,316 (Hut 8 9,314 + ABTC 8,002; 7,940 pledged). "
                "NCI (46.37% of ABTC) added at book $311.4m — ABTC's market value is not captured (WARN). JPMorgan $1.07bn revolver (2026-09-24) undrawn.")),
]

COHORT_LABEL = {"A": "A — BTC-mining weighted", "B": "B — HPC/AI-pivot"}
BASIS_LABEL = {"G": "gross utility MW as disclosed", "U": "utilized load MW (company metric; nameplate not disclosed)",
               "IT->G": "critical-IT MW converted to gross at 1.30 (Assumption)"}

# -------------------------------------------------------------------- engine
def compute(c, spot=PARAMS["btc_spot_usd"]):
    shares = c["shares_m"] + c["pf_shares_m"]
    mc = c["price"] * shares
    debt = c["debt_face"] + c["pf_debt"]
    cash = c["cash"] + c["restricted"] + c["pf_cash"]
    ev = mc + debt + c["nci"] - cash
    btc_val = c["btc"] * spot / 1e6
    infra = ev - btc_val
    out = dict(shares_m=shares, mc=mc, debt=debt, cash=cash, ev=ev, btc_val=btc_val, infra=infra,
               infra_share=(infra / ev) if ev else None,
               nonrec_pct=(c["nonrecourse"] / debt) if debt else 0.0,
               restricted_pct=((c["restricted"]) / debt) if debt else 0.0)
    for num_name, num in (("mc", mc), ("ev", ev), ("infra", infra)):
        for d in ("d1", "d2", "d3"):
            out[f"{num_name}_per_{d}"] = num / c[d]
    return out

def all_metrics(companies=COMPANIES, spot=PARAMS["btc_spot_usd"]):
    return {c["ticker"]: compute(c, spot) for c in companies}

def median(xs):
    xs = sorted(x for x in xs if x is not None)
    n = len(xs)
    if n == 0: return None
    return xs[n//2] if n % 2 else 0.5 * (xs[n//2 - 1] + xs[n//2])

def inputs_payload():
    return {"standard": "HASHFLOPS Mining Capacity Standard", "version": VERSION, "data_cut": DATA_CUT, "release": RELEASE,
            "params": PARAMS, "companies": COMPANIES}

def fingerprint(payload=None):
    payload = dict(payload or inputs_payload())
    payload.pop("fingerprint", None)          # the stored fingerprint is not part of the fingerprinted content
    s = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(s.encode("utf-8")).hexdigest()

if __name__ == "__main__":
    m = all_metrics()
    print(f"{'TKR':<5}{'MC':>8}{'Debt':>8}{'Cash':>8}{'EV':>8}{'BTC$':>7}{'Infra':>8} | {'EV/D1':>6}{'EV/D2':>6}{'EV/D3':>6} | {'Fe/D1':>6}{'Fe/D2':>6}{'Fe/D3':>6}")
    for t, r in m.items():
        print(f"{t:<5}{r['mc']:>8.0f}{r['debt']:>8.0f}{r['cash']:>8.0f}{r['ev']:>8.0f}{r['btc_val']:>7.0f}{r['infra']:>8.0f} | "
              f"{r['ev_per_d1']:>6.2f}{r['ev_per_d2']:>6.2f}{r['ev_per_d3']:>6.2f} | {r['infra_per_d1']:>6.2f}{r['infra_per_d2']:>6.2f}{r['infra_per_d3']:>6.2f}")
    print("fingerprint:", fingerprint())
