"""Build Mining_Capacity_Standard_v1.0_<data_cut>.xlsx from capacity_common data set (audit trail: workbook is derived, JSON is primary)."""
import sys, os, datetime
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter as L
from openpyxl.worksheet.formula import ArrayFormula
from openpyxl.formatting.rule import ColorScaleRule
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import capacity_common as cc

OUT = sys.argv[1] if len(sys.argv) > 1 else f"Mining_Capacity_Standard_v{cc.VERSION}_{cc.DATA_CUT}.xlsx"

NAVY = "1F4E78"; GREY = "D9E1F2"; DARK = "404040"
F_HDR = Font(name="Arial", bold=True, size=10, color="FFFFFF")
F_T = Font(name="Arial", bold=True, size=14, color=NAVY)
F_SUB = Font(name="Arial", italic=True, size=9, color="595959")
F_IN = Font(name="Arial", size=10, color="0000FF")          # input
F_ASM = Font(name="Arial", size=10, color="0000FF")         # assumption (blue + yellow fill)
F_FX = Font(name="Arial", size=10, color="000000")          # formula
F_XS = Font(name="Arial", size=10, color="008000")          # cross-sheet
F_B = Font(name="Arial", bold=True, size=10)
F_N = Font(name="Arial", size=10)
FILL_HDR = PatternFill("solid", start_color=NAVY); FILL_SUB = PatternFill("solid", start_color=DARK)
FILL_GREY = PatternFill("solid", start_color=GREY); FILL_YEL = PatternFill("solid", start_color="FFFF99")
FILL_WARN = PatternFill("solid", start_color="FFEB9C"); FILL_ERR = PatternFill("solid", start_color="FFC7CE"); FILL_OK = PatternFill("solid", start_color="C6EFCE")
CENTER = Alignment(horizontal="center", vertical="center", wrap_text=True)
WRAP = Alignment(wrap_text=True, vertical="top")
THIN = Side(style="thin", color="BFBFBF"); BOX = Border(top=THIN, bottom=THIN, left=THIN, right=THIN)

def hdr(ws, row, labels, fill=FILL_HDR, height=30):
    for i, h in enumerate(labels, start=1):
        c = ws.cell(row, i, h); c.font = F_HDR; c.fill = fill; c.alignment = CENTER; c.border = BOX
    ws.row_dimensions[row].height = height

def title(ws, text, sub=None, span=12):
    ws["A1"] = text; ws["A1"].font = F_T; ws.merge_cells(start_row=1, end_row=1, start_column=1, end_column=span)
    if sub:
        ws["A2"] = sub; ws["A2"].font = F_SUB; ws["A2"].alignment = WRAP
        ws.merge_cells(start_row=2, end_row=2, start_column=1, end_column=span); ws.row_dimensions[2].height = 42

def widths(ws, ws_widths):
    for col, w in ws_widths.items(): ws.column_dimensions[col].width = w

wb = Workbook()
N = len(cc.COMPANIES); R0 = 5; R1 = R0 + N - 1   # data rows 5..14

# ============================================================ Public_Summary
PS = wb.active; PS.title = "Public_Summary"
PS.sheet_view.showGridLines = False
title(PS, f"Enterprise Value and Infrastructure Value per Megawatt — Public Bitcoin Miners, data cut {cc.DATA_CUT}",
      f"HASHFLOPS Mining Capacity Standard v{cc.VERSION} · release {cc.RELEASE} · BTC spot ${cc.PARAMS['btc_spot_usd']:,.2f} · "
      "balance sheets 2026-06-30 (10-Q/10-K/6-K) plus disclosed subsequent events · capacity per company disclosures through the data cut. "
      "All figures live-linked to the Metrics sheet; the only published output is this sheet.", span=14)
PS["A4"] = "Headline — ranked by Infrastructure value per Committed MW (24-month horizon), cheapest first"
PS["A4"].font = F_B
hdr(PS, 5, ["#", "Ticker", "Cohort", "Market cap $m", "EV $m", "BTC @spot $m", "Infrastructure value $m",
            "Energized MW", "Committed MW (≤24m)", "Portfolio MW", "EV / Energized $m/MW", "EV / Committed $m/MW",
            "Infra / Committed $m/MW", "Infra / Portfolio $m/MW"], height=44)
for i in range(1, N + 1):
    r = 5 + i
    PS.cell(r, 1, i).alignment = CENTER
    PS.cell(r, 2, f"=Ranking!B{4+i}").font = F_XS
    for col, src in zip(range(3, 15), ["C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"]):
        c = PS.cell(r, col, f"=Ranking!{src}{4+i}"); c.font = F_XS
        c.number_format = '#,##0' if col in (4,5,6,7,8,9,10) else '0.00'
        c.alignment = Alignment(horizontal="center")
    PS.cell(r, 2).alignment = Alignment(horizontal="center")
rm = 6 + N
for lab, src_row in (("Median — all 10", 16), ("Median — cohort A (BTC-mining weighted)", 17), ("Median — cohort B (HPC/AI-pivot)", 18)):
    PS.cell(rm, 2, lab).font = F_B
    PS.merge_cells(start_row=rm, end_row=rm, start_column=2, end_column=10)
    for col, src in ((11, "O"), (12, "P"), (13, "S"), (14, "T")):
        c = PS.cell(rm, col, f"=Metrics!{src}{src_row}"); c.font = Font(name="Arial", bold=True, color="008000"); c.number_format = '0.00'
        c.alignment = Alignment(horizontal="center")
    for col in range(2, 15): PS.cell(rm, col).fill = FILL_GREY
    rm += 1
rule = ColorScaleRule(start_type="min", start_color="63BE7B", mid_type="percentile", mid_value=50, mid_color="FFEB84", end_type="max", end_color="F8696B")
for col in ("K", "L", "M", "N"): PS.conditional_formatting.add(f"{col}6:{col}{5+N}", rule)

txt_r = rm + 1
notes = [
 "How to read. EV = market capitalisation (close × basic shares, pro forma for disclosed post-quarter issuance) + face debt (pro forma for disclosed post-quarter issues/repayments) + "
 "non-controlling interests at book − cash including RESTRICTED cash. Infrastructure value = EV − bitcoin held × spot: what the market pays for data centres, substations, grid "
 "rights, miners and contracted power — not for financial assets. Restricted cash is deducted because ~$14bn of project-note proceeds raised in Q2 2026 (HUT, CIFR, CORZ, WULF, IREN) "
 "sit in construction/reserve accounts and are not yet infrastructure; aggregators that ignore it overstate EV for exactly the companies with the largest build programmes.",
 "Three denominators. Energized MW = grid-connected utility capacity at company-controlled sites as disclosed (basis G); where a company reports only utilized load (CLSK) or "
 "critical-IT MW (CORZ) the basis is flagged (U / IT→G at 1.30). Committed MW = Energized + capacity under construction or contracted for energization within 24 months of the "
 "data cut (by 2028-10-15). Portfolio MW = the company's own total development pipeline incl. sites under diligence/exclusivity/option. Per-site reconciliation: sheet Capacity.",
 "Reading the spread. Cohort A miners trade at $1–3.5m of infrastructure value per committed MW; cohort B HPC-pivot companies at $4.3–9.2m, converging toward $1–3m on portfolio MW. "
 "A large gap between the Energized and Committed multiples (WULF, HUT, CORZ, CIFR) means the market is paying for construction in progress and signed leases; a large gap between "
 "Committed and Portfolio (HUT, CIFR, MARA) means it is paying for optionality that has no contracted tenant yet.",
 "Not a valuation. Capacity multiples compare the price of power infrastructure across business models; they do not adjust for contracted revenue per MW (HPC leases earn 5–10× "
 "mining revenue per MW), tenant credit, or capex still to be spent on committed MW. No fair values, recommendations or target prices are expressed or implied.",
]
for t in notes:
    PS.cell(txt_r, 1, t).font = F_N; PS.cell(txt_r, 1).alignment = WRAP
    PS.merge_cells(start_row=txt_r, end_row=txt_r, start_column=1, end_column=14); PS.row_dimensions[txt_r].height = 58; txt_r += 1
txt_r += 1
PS.cell(txt_r, 1, "Model integrity").font = F_B; txt_r += 1
for lab, ref in (("Standard version", "=Version_Log!B4"), ("Data cut", "=Version_Log!B5"), ("Release", "=Version_Log!B6"),
                 ("Inputs fingerprint (SHA-256)", "=Version_Log!B7"), ("LibreOffice recalc", "=Version_Log!B8"), ("Engine compare", "=Version_Log!B9"),
                 ("Checks", "=Version_Log!B10"), ("Verdict", "=Version_Log!B11")):
    PS.cell(txt_r, 1, lab).font = F_N; PS.cell(txt_r, 3, ref).font = F_XS
    PS.merge_cells(start_row=txt_r, end_row=txt_r, start_column=3, end_column=14); txt_r += 1
txt_r += 1
PS.cell(txt_r, 1, "Disclaimer").font = F_B; txt_r += 1
disc = [
 "1. Informational research; not investment advice, not an offer or solicitation; no recommendations, target prices or signals are made or implied.",
 "2. All figures are derived from issuers' SEC filings and disclosed subsequent events under the published Standard; capacity figures follow each issuer's own definitions (energized, "
 "under construction, pipeline) and are not independently verified; basis conversions (IT→gross) are assumptions and are flagged.",
 "3. Sources are cited per input (sheets Data, Capacity, Sources); figures may be revised when issuers restate or when extraction errors are found (errata published with the next release; prior versions retained).",
 "4. Conflict of interest: the author may hold positions in companies covered; existence of a position is disclosed on the publication page, size is not; no trading ±2 trading days around publication.",
 "5. Readers are encouraged to reproduce the results from the reproducibility package (inputs JSON with SHA-256 fingerprint, independent Python engine, validation script and log).",
]
for t in disc:
    PS.cell(txt_r, 1, t).font = F_SUB; PS.cell(txt_r, 1).alignment = WRAP
    PS.merge_cells(start_row=txt_r, end_row=txt_r, start_column=1, end_column=14); PS.row_dimensions[txt_r].height = 30; txt_r += 1
widths(PS, {"A": 5, "B": 9, "C": 9, "D": 13, "E": 11, "F": 12, "G": 15, "H": 12, "I": 13, "J": 12, "K": 14, "L": 14, "M": 14, "N": 14})
PS.freeze_panes = "A6"

# ============================================================ Version_Log
VL = wb.create_sheet("Version_Log")
title(VL, "Version Log", "Stamped by validate_capacity.py after LibreOffice recalculation and engine comparison. Inputs fingerprint = SHA-256 of the canonical inputs JSON.", span=4)
rows = [("Standard version", cc.VERSION), ("Data cut", cc.DATA_CUT), ("Release", cc.RELEASE), ("Inputs fingerprint (SHA-256)", cc.fingerprint()),
        ("LibreOffice recalc", "PENDING"), ("Engine compare", "PENDING"), ("Checks", "PENDING"), ("Verdict", "PENDING"), ("Validated at (UTC)", "PENDING"),
        ("Workbook built at (UTC)", datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC"))]
for i, (k, v) in enumerate(rows, start=4):
    VL.cell(i, 1, k).font = F_B; VL.cell(i, 2, v).font = F_N
VL.cell(16, 1, "Change log").font = F_B
VL.cell(17, 1, "1.0").font = F_N
VL.cell(17, 2, f"{cc.RELEASE} — first release. Supersedes the internal peer workbook Miners_Analytics_AllCompanies v1–v11 (May–Sept 2026): same six-multiple framework "
               "(Market cap and EV over Energized / Committed / Portfolio MW) plus Infrastructure value (EV − BTC) multiples, now on the shared HASHFLOPS data cut, with "
               "face debt, restricted cash deducted, NCI added, basis codes for MW, and a reproducibility package.").font = F_N
VL.cell(17, 2).alignment = WRAP; VL.merge_cells("B17:D17"); VL.row_dimensions[17].height = 70
widths(VL, {"A": 30, "B": 70, "C": 20, "D": 20})

# ============================================================ Standard
ST = wb.create_sheet("Standard")
title(ST, f"HASHFLOPS Mining Capacity Standard v{cc.VERSION} — rules", "Normative text. A change to any rule is a major version; a data refresh is a minor version.", span=3)
rules = [
 ("1 Scope", "Public companies whose primary assets are power-connected data-centre sites originally built for Bitcoin mining: BTDR, MARA, CLSK, IREN, RIOT, CORZ, CIFR, HIVE, WULF, HUT. "
             "Two cohorts: A = BTC-mining weighted (mining revenue > HPC revenue in H1 2026 and no multi-GW contracted HPC programme); B = HPC/AI-pivot. Medians are published for all and per cohort (min n = 5 for 'all')."),
 ("2 Data cut", "One data cut for all inputs: equity price = exchange close on the data-cut date (≤5 days, else WARN); BTC spot = one provider with UTC timestamp; balance sheet = latest filed "
                "10-Q/10-K/6-K (≤120 days, else WARN); capacity = company disclosures through the data cut. The same cut is shared with the Mining NAV and Mining Cost Standards."),
 ("3 Market capitalisation", "Close × basic shares outstanding from the latest cover page / proxy, pro forma for disclosed post-quarter issuance or exchanges (shares and cash/debt adjusted symmetrically). "
                             "No TSM/if-converted dilution in capacity multiples (it is a price of the equity as traded)."),
 ("4 Debt", "Face (principal) value of borrowings as filed, incl. project-level notes consolidated by the issuer, BTC-collateralised loans and converts; excl. leases, warrant liabilities, deferred "
            "revenue and miner-purchase liabilities settled in pledged BTC. Pro forma for disclosed post-quarter issues/repayments (added to both debt and cash at net proceeds where disclosed)."),
 ("5 Cash", "Cash and cash equivalents PLUS restricted cash (construction and debt-service reserve accounts). Rationale: undisbursed project-note proceeds are not infrastructure; deducting them "
            "keeps EV comparable between a company that has raised its construction financing and one that has not. Deposits, prepayments and BTC are not cash."),
 ("6 Non-controlling interests", "Added to EV at book value as filed (mezzanine redeemable NCI included). Where a consolidated subsidiary is listed (HUT/ABTC) book value may understate the minority — WARN."),
 ("7 EV and Infrastructure value", "EV = Market cap + Debt + NCI − Cash. Bitcoin value = BTC held (incl. pledged/loaned, excl. BTC held by vendors under repurchase options) × spot. "
                                   "Infrastructure value = EV − Bitcoin value. Negative infrastructure value is reported as is (it means the market prices the operating business below its BTC)."),
 ("8 Denominators", "D1 Energized MW = grid-connected utility capacity at company-controlled sites as the company discloses it ('energized', 'online electrical', 'developed', 'energy capacity under "
                    "management'). D2 Committed MW = D1 + capacity under construction or contracted for energization within 24 months of the data cut. D3 Portfolio MW = the company's own total "
                    "development pipeline incl. diligence/exclusivity/options. D1 ≤ D2 ≤ D3 is an invariant (ERROR). Each D1 carries a basis code: G gross as disclosed; U utilized load (nameplate "
                    "not disclosed); IT→G critical-IT MW converted at the company's own gross/IT ratio where disclosed, else at the Standard default 1.30 (Assumption, flagged)."),
 ("9 Metrics", "Nine multiples in $m per MW: {Market cap, EV, Infrastructure value} ÷ {D1, D2, D3}. Headline = Infrastructure value / Committed MW (most stable denominator: realistically "
               "deliverable within two years, least sensitive to pipeline announcements). Also: infrastructure share of EV, non-recourse share of debt, restricted cash / debt."),
 ("10 Facts vs assumptions", "Every input carries a source ID (sheet Sources) with filing type, date and URL. Assumptions (IT→G factor, timing within 24 months) are blue-on-yellow and listed in Checks as WARN."),
 ("11 Verification", "Two independent paths: LibreOffice full recalculation (0 formula errors required) and the Python engine capacity_engine.py recomputing every derived value from the inputs JSON "
                     "(no Excel formulas executed), compared cell by cell at tolerance 0.005. Version Log records both statuses, the inputs fingerprint and the verdict (READY / NOT READY)."),
 ("12 Publication", "Only the Public Summary is published. No fair values, recommendations, target prices or signals. Mandatory caveats: restricted-cash deduction, basis codes, NCI at book, "
                    "capacity figures are issuer definitions not verified by HASHFLOPS. Errata: a note above the page; prior versions retained with their fingerprints."),
 ("13 Refresh triggers", "10-Q/10-K/6-K (10 business days); capacity disclosure or financing ≥10% of EV (5 days); BTC ±20% or price move ±20% in the set (5 days); error (immediately, errata); quarterly review."),
]
hdr(ST, 4, ["Rule", "Text", "Status"])
for i, (k, v) in enumerate(rules, start=5):
    ST.cell(i, 1, k).font = F_B; ST.cell(i, 1).alignment = WRAP
    ST.cell(i, 2, v).font = F_N; ST.cell(i, 2).alignment = WRAP
    ST.cell(i, 3, "normative").font = F_SUB
    ST.row_dimensions[i].height = 78
widths(ST, {"A": 24, "B": 130, "C": 12})

# ============================================================ Data
DT = wb.create_sheet("Data")
title(DT, f"Inputs — data cut {cc.DATA_CUT} (blue = input from source; blue on yellow = assumption; black = formula; green = cross-sheet)",
      "USD millions, millions of shares, MW. Sources: sheet Sources (IDs per company). Pro forma (PF) columns hold disclosed post-quarter events only.", span=24)
DT["A3"] = "BTC spot, USD"; DT["A3"].font = F_B
DT["B3"] = cc.PARAMS["btc_spot_usd"]; DT["B3"].font = F_IN; DT["B3"].number_format = '#,##0.00'
DT["C3"] = cc.PARAMS["btc_spot_source"]; DT["C3"].font = F_SUB
DT["H3"] = "IT→G default"; DT["H3"].font = F_B
DT["I3"] = cc.PARAMS["it_to_gross_default"]; DT["I3"].font = F_ASM; DT["I3"].fill = FILL_YEL; DT["I3"].number_format = '0.00'
DT["J3"] = "Assumption — used only for CORZ (no gross utility disclosure)"; DT["J3"].font = F_SUB
cols = ["Ticker", "Company", "Cohort", "Price $ (close)", "Shares basic, m", "PF shares, m", "Debt face $m", "PF debt $m", "Cash $m",
        "Restricted cash $m", "PF cash $m", "NCI $m (book)", "BTC held", "BTC pledged/loaned (info)", "Non-recourse debt $m",
        "D1 Energized MW", "D1 basis", "D2 Committed MW (≤24m)", "D3 Portfolio MW", "Hashrate EH/s (info)", "Balance sheet date", "Filing", "Filed", "Confidence"]
hdr(DT, 4, cols, height=44)
for i, c in enumerate(cc.COMPANIES):
    r = R0 + i
    vals = [c["ticker"], c["company"], c["cohort"], c["price"], c["shares_m"], c["pf_shares_m"], c["debt_face"], c["pf_debt"], c["cash"],
            c["restricted"], c["pf_cash"], c["nci"], c["btc"], c["btc_pledged"], c["nonrecourse"], c["d1"], c["d1_basis"], c["d2"], c["d3"],
            c["hashrate_ehs"] if c["hashrate_ehs"] is not None else "n/d", c["bs_date"], c["filing"], c["filed"], c["conf"]]
    for j, v in enumerate(vals, start=1):
        cell = DT.cell(r, j, v); cell.border = BOX
        cell.font = F_IN if j in (4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20) else F_N
        if j == 1: cell.font = F_B
        if j in (4,): cell.number_format = '0.00'
        if j in (5, 6): cell.number_format = '#,##0.000'
        if j in (7, 8, 9, 10, 11, 12, 15): cell.number_format = '#,##0.0'
        if j in (13, 14, 16, 18, 19): cell.number_format = '#,##0'
        if j in (3, 17, 21, 23, 24): cell.alignment = Alignment(horizontal="center")
    # assumption highlighting: converted MW and PF estimates
    if c["d1_basis"] != "G":
        for j in (16,): DT.cell(r, j).fill = FILL_YEL
    if c["d1_basis"] == "IT->G":
        for j in (18, 19): DT.cell(r, j).fill = FILL_YEL
    if c["ticker"] == "CLSK":
        DT.cell(r, 11).fill = FILL_YEL   # net proceeds estimate
    if c["ticker"] == "HIVE":
        DT.cell(r, 5).fill = FILL_YEL    # aggregator share count
widths(DT, {"A": 7, "B": 30, "C": 7, "D": 9, "E": 11, "F": 9, "G": 10, "H": 9, "I": 9, "J": 11, "K": 9, "L": 9, "M": 9, "N": 11, "O": 11,
            "P": 10, "Q": 7, "R": 11, "S": 11, "T": 9, "U": 11, "V": 40, "W": 11, "X": 9})
DT.freeze_panes = "D5"

# ============================================================ Capacity (per-site reconciliation)
CP = wb.create_sheet("Capacity")
title(CP, "Capacity reconciliation — how D1 / D2 / D3 are built for each company",
      "Company definitions quoted; additions within the 24-month window listed; exclusions stated. Basis G = gross utility; U = utilized; IT→G = converted.", span=8)
hdr(CP, 4, ["Ticker", "Cohort", "D1 Energized MW", "Basis", "D2 Committed MW", "D3 Portfolio MW", "D3 / D1", "Reconciliation and sources"], height=36)
for i, c in enumerate(cc.COMPANIES):
    r = R0 + i
    CP.cell(r, 1, f"=Data!A{r}").font = F_XS; CP.cell(r, 2, f"=Data!C{r}").font = F_XS
    CP.cell(r, 3, f"=Data!P{r}").font = F_XS; CP.cell(r, 4, f"=Data!Q{r}").font = F_XS
    CP.cell(r, 5, f"=Data!R{r}").font = F_XS; CP.cell(r, 6, f"=Data!S{r}").font = F_XS
    CP.cell(r, 7, f"=IF(C{r}>0,F{r}/C{r},\"\")").font = F_FX; CP.cell(r, 7).number_format = '0.0"×"'
    CP.cell(r, 8, c["mw_note"]).font = F_N; CP.cell(r, 8).alignment = WRAP
    for j in (3, 5, 6): CP.cell(r, j).number_format = '#,##0'
    for j in range(1, 8): CP.cell(r, j).alignment = Alignment(horizontal="center", vertical="top")
    CP.row_dimensions[r].height = 118
sr = R1 + 1
CP.cell(sr, 1, "Σ set").font = F_B
for j, col in ((3, "C"), (5, "E"), (6, "F")):
    CP.cell(sr, j, f"=SUM({col}{R0}:{col}{R1})").font = F_B; CP.cell(sr, j).number_format = '#,##0'; CP.cell(sr, j).fill = FILL_GREY
CP.cell(sr, 7, f"=F{sr}/C{sr}").font = F_B; CP.cell(sr, 7).number_format = '0.0"×"'; CP.cell(sr, 7).fill = FILL_GREY
widths(CP, {"A": 7, "B": 7, "C": 11, "D": 7, "E": 12, "F": 12, "G": 8, "H": 140})
CP.freeze_panes = "A5"

# ============================================================ Metrics
MT = wb.create_sheet("Metrics")
title(MT, "Metrics — formulas only (every cell is recomputed by capacity_engine.py)",
      "EV = MC + Debt + NCI − Cash (incl. restricted). Infrastructure value = EV − BTC × spot. Multiples in $m per MW.", span=25)
mcols = ["Ticker", "Cohort", "Shares m (PF)", "Market cap $m", "Debt $m (PF)", "Cash $m (PF, incl. restricted)", "NCI $m", "EV $m", "BTC value $m",
         "Infrastructure value $m", "Infra share of EV", "MC / D1", "MC / D2", "MC / D3", "EV / D1", "EV / D2", "EV / D3", "Infra / D1", "Infra / D2", "Infra / D3",
         "Non-recourse % of debt", "Restricted cash / debt", "D1 MW", "D2 MW", "D3 MW"]
hdr(MT, 4, mcols, height=44)
for i in range(N):
    r = R0 + i
    f = {
        1: f"=Data!A{r}", 2: f"=Data!C{r}", 3: f"=Data!E{r}+Data!F{r}", 4: f"=Data!D{r}*C{r}", 5: f"=Data!G{r}+Data!H{r}",
        6: f"=Data!I{r}+Data!J{r}+Data!K{r}", 7: f"=Data!L{r}", 8: f"=D{r}+E{r}+G{r}-F{r}", 9: f"=Data!M{r}*Data!$B$3/1000000",
        10: f"=H{r}-I{r}", 11: f"=IF(H{r}<>0,J{r}/H{r},\"\")",
        12: f"=D{r}/W{r}", 13: f"=D{r}/X{r}", 14: f"=D{r}/Y{r}", 15: f"=H{r}/W{r}", 16: f"=H{r}/X{r}", 17: f"=H{r}/Y{r}",
        18: f"=J{r}/W{r}", 19: f"=J{r}/X{r}", 20: f"=J{r}/Y{r}",
        21: f"=IF(E{r}>0,Data!O{r}/E{r},0)", 22: f"=IF(E{r}>0,Data!J{r}/E{r},0)",
        23: f"=Data!P{r}", 24: f"=Data!R{r}", 25: f"=Data!S{r}",
    }
    for j, fx in f.items():
        cell = MT.cell(r, j, fx); cell.border = BOX
        cell.font = F_XS if fx.startswith("=Data!") else F_FX
        if j == 3: cell.number_format = '#,##0.0'
        elif j in (4,5,6,7,8,9,10): cell.number_format = '#,##0'
        elif j in (11, 21, 22): cell.number_format = '0%'
        elif 12 <= j <= 20: cell.number_format = '0.00'
        elif j >= 23: cell.number_format = '#,##0'
        cell.alignment = Alignment(horizontal="center")
    MT.cell(r, 1).font = F_B
# medians
med_rows = [(16, "Median — all", None), (17, "Median — cohort A", "A"), (18, "Median — cohort B", "B")]
for rr, lab, coh in med_rows:
    MT.cell(rr, 1, lab).font = F_B; MT.merge_cells(start_row=rr, end_row=rr, start_column=1, end_column=3)
    for j in list(range(12, 21)) + [11, 21, 22]:
        col = L(j)
        if coh is None:
            MT.cell(rr, j, f"=MEDIAN({col}{R0}:{col}{R1})")
        else:
            MT.cell(rr, j).value = ArrayFormula(f"{col}{rr}", f'=MEDIAN(IF($B${R0}:$B${R1}="{coh}",{col}{R0}:{col}{R1}))')
        MT.cell(rr, j).font = F_B; MT.cell(rr, j).number_format = '0%' if j in (11, 21, 22) else '0.00'
        MT.cell(rr, j).alignment = Alignment(horizontal="center")
    for j in range(1, 26): MT.cell(rr, j).fill = FILL_GREY
# sums
MT.cell(20, 1, "Σ set").font = F_B
for j in (4, 5, 6, 7, 8, 9, 10, 23, 24, 25):
    col = L(j); MT.cell(20, j, f"=SUM({col}{R0}:{col}{R1})").font = F_B; MT.cell(20, j).number_format = '#,##0'; MT.cell(20, j).alignment = Alignment(horizontal="center")
MT.cell(20, 11, "=J20/H20").font = F_B; MT.cell(20, 11).number_format = '0%'
for j in range(12, 21): cf = ColorScaleRule(start_type="min", start_color="63BE7B", mid_type="percentile", mid_value=50, mid_color="FFEB84", end_type="max", end_color="F8696B"); MT.conditional_formatting.add(f"{L(j)}{R0}:{L(j)}{R1}", cf)
widths(MT, {"A": 7, "B": 7, "C": 10, "D": 11, "E": 10, "F": 13, "G": 8, "H": 10, "I": 10, "J": 13, "K": 9, **{L(j): 8 for j in range(12, 23)}, "W": 9, "X": 9, "Y": 9})
MT.freeze_panes = "C5"

# ============================================================ Ranking
RK = wb.create_sheet("Ranking")
title(RK, "Ranking — Infrastructure value per Committed MW (ascending = cheapest infrastructure first)",
      "Formula-driven from Metrics (INDEX/MATCH on SMALL). Percentile = position in the 10-company set (0% cheapest).", span=16)
hdr(RK, 4, ["#", "Ticker", "Cohort", "Market cap $m", "EV $m", "BTC @spot $m", "Infra value $m", "D1 MW", "D2 MW", "D3 MW",
            "EV / D1", "EV / D2", "Infra / D2", "Infra / D3", "Percentile (Infra/D2)", "D1 basis / confidence"], height=40)
for i in range(1, N + 1):
    r = 4 + i
    RK.cell(r, 1, i).alignment = CENTER
    RK.cell(r, 2, f"=INDEX(Metrics!$A${R0}:$A${R1},MATCH(SMALL(Metrics!$S${R0}:$S${R1},{i}),Metrics!$S${R0}:$S${R1},0))").font = F_B
    m = f"MATCH($B{r},Metrics!$A${R0}:$A${R1},0)"
    for j, col in zip(range(3, 15), ["B", "D", "H", "I", "J", "W", "X", "Y", "O", "P", "S", "T"]):
        c = RK.cell(r, j, f"=INDEX(Metrics!${col}${R0}:${col}${R1},{m})"); c.font = F_XS; c.alignment = Alignment(horizontal="center")
        c.number_format = '#,##0' if j in (4,5,6,7,8,9,10) else '0.00'
    RK.cell(r, 15, f"=PERCENTRANK(Metrics!$S${R0}:$S${R1},M{r})").number_format = '0%'; RK.cell(r, 15).alignment = Alignment(horizontal="center")
    RK.cell(r, 16, f"=INDEX(Data!$Q${R0}:$Q${R1},{m})&\" / \"&INDEX(Data!$X${R0}:$X${R1},{m})").font = F_XS; RK.cell(r, 16).alignment = Alignment(horizontal="center")
    RK.cell(r, 2).alignment = Alignment(horizontal="center")
for col in ("K", "L", "M", "N"): RK.conditional_formatting.add(f"{col}5:{col}{4+N}", ColorScaleRule(start_type="min", start_color="63BE7B", mid_type="percentile", mid_value=50, mid_color="FFEB84", end_type="max", end_color="F8696B"))
widths(RK, {"A": 5, "B": 8, "C": 7, "D": 12, "E": 10, "F": 11, "G": 12, "H": 9, "I": 9, "J": 9, "K": 9, "L": 9, "M": 10, "N": 10, "O": 12, "P": 14})
RK.freeze_panes = "C5"

# ============================================================ Checks
CK = wb.create_sheet("Checks")
title(CK, "Checks — ERROR blocks release; WARN goes to the release note", "Formula-driven; the engine comparison line is written by validate_capacity.py.", span=5)
hdr(CK, 4, ["#", "Check", "Scope", "Result", "Detail"])
rowc = 5
def add_check(name, scope, formula, detail):
    global rowc
    CK.cell(rowc, 1, rowc - 4); CK.cell(rowc, 2, name).font = F_N; CK.cell(rowc, 3, scope).font = F_N
    CK.cell(rowc, 4, formula).font = F_FX; CK.cell(rowc, 4).alignment = Alignment(horizontal="center")
    CK.cell(rowc, 5, detail).font = F_SUB; CK.cell(rowc, 5).alignment = WRAP
    rowc += 1
# invariants per company
for i, c in enumerate(cc.COMPANIES):
    r = R0 + i; t = c["ticker"]
    add_check("Invariant D1 ≤ D2 ≤ D3", t, f'=IF(AND(Data!P{r}<=Data!R{r},Data!R{r}<=Data!S{r}),"PASS","ERROR")', "Rule 8")
    add_check("EV reconciliation (MC+Debt+NCI−Cash)", t, f'=IF(ABS(Metrics!H{r}-(Metrics!D{r}+Metrics!E{r}+Metrics!G{r}-Metrics!F{r}))<0.005,"PASS","ERROR")', "Rule 7")
    add_check("Positive inputs (price, shares, MW)", t, f'=IF(AND(Data!D{r}>0,Data!E{r}+Data!F{r}>0,Data!P{r}>0),"PASS","ERROR")', "")
    add_check("Infrastructure value ≥ 0", t, f'=IF(Metrics!J{r}>=0,"PASS","WARN")', "Negative = market prices operations below BTC held (reported as is)")
    add_check("Balance sheet ≤ 120 days from data cut", t, f'=IF(DATEVALUE("{cc.DATA_CUT}")-DATEVALUE(Data!U{r})<={cc.PARAMS["stale_bs_days"]},"PASS","WARN")', "Rule 2")
    add_check("D1 basis is gross (G)", t, f'=IF(Data!Q{r}="G","PASS","WARN")', "U = utilized load; IT→G = converted at 1.30 (Assumption)")
    add_check("Confidence not C", t, f'=IF(Data!X{r}<>"C","PASS","WARN")', "C = reconstructed / converted capacity or market inputs")
    add_check("Pro forma events applied", t, f'=IF(AND(Data!F{r}=0,Data!H{r}=0,Data!K{r}=0),"PASS","WARN")', "Disclosed post-quarter issuance / repayment / exchange — see Data notes")
    add_check("Restricted cash ≤ 50% of debt", t, f'=IF(Metrics!V{r}<=0.5,"PASS","WARN")', "Large escrowed project-note proceeds: EV very sensitive to the restricted-cash rule")
    add_check("NCI at book", t, f'=IF(Data!L{r}=0,"PASS","WARN")', "Book NCI may understate a listed subsidiary minority (HUT/ABTC)")
add_check("Share count source", "HIVE", '="WARN"', "Basic shares 267.43m from market-data aggregators (2026-07-23/30); 10-Q cover count not captured in the shared data set")
add_check("Engine compare (capacity_engine.py)", "all", '=Version_Log!B9', "Written by validate_capacity.py")
add_check("LibreOffice recalc", "all", '=Version_Log!B8', "Written by validate_capacity.py")
# summary
sr_ = rowc + 1
CK.cell(sr_, 2, "Summary").font = F_B
CK.cell(sr_ + 1, 2, "PASS"); CK.cell(sr_ + 1, 4, f'=COUNTIF(D5:D{rowc-1},"PASS")')
CK.cell(sr_ + 2, 2, "WARN"); CK.cell(sr_ + 2, 4, f'=COUNTIF(D5:D{rowc-1},"WARN")')
CK.cell(sr_ + 3, 2, "ERROR"); CK.cell(sr_ + 3, 4, f'=COUNTIF(D5:D{rowc-1},"ERROR")')
CK.cell(sr_ + 4, 2, "Release gate"); CK.cell(sr_ + 4, 4, f'=IF(D{sr_+3}=0,"NO ERROR","BLOCKED")'); CK.cell(sr_ + 4, 4).font = F_B
for rr in range(sr_ + 1, sr_ + 5): CK.cell(rr, 2).font = F_B; CK.cell(rr, 4).alignment = Alignment(horizontal="center")
from openpyxl.formatting.rule import CellIsRule
CK.conditional_formatting.add(f"D5:D{rowc-1}", CellIsRule(operator="equal", formula=['"ERROR"'], fill=FILL_ERR))
CK.conditional_formatting.add(f"D5:D{rowc-1}", CellIsRule(operator="equal", formula=['"WARN"'], fill=FILL_WARN))
CK.conditional_formatting.add(f"D5:D{rowc-1}", CellIsRule(operator="equal", formula=['"PASS"'], fill=FILL_OK))
widths(CK, {"A": 5, "B": 40, "C": 8, "D": 12, "E": 90})
CK.freeze_panes = "A5"

# ============================================================ Sources
SO = wb.create_sheet("Sources")
title(SO, "Sources — one line per company input set, plus market and spot sources", "All balance-sheet inputs are the Mining NAV Standard v1.1 data set (collected 2026-10-15/17 from EDGAR); capacity inputs cite the filing/release used.", span=6)
hdr(SO, 4, ["ID", "Ticker", "Title", "Date", "URL", "Used for"])
SRC = [
 ("S-BTDR-1", "BTDR", "Bitdeer 6-K — Q2 2026 results (Ex. 99.1), Power Infrastructure Summary as of 2026-07-31", "2026-08-10", "https://www.sec.gov/Archives/edgar/data/1899123/000121390026086938/ea030131301ex99-1.htm", "D1/D2/D3, hashrate, BTC held, borrowings"),
 ("S-BTDR-2", "BTDR", "Bitdeer 6-K — H1 2026 US GAAP financial statements and recent developments (Ex. 99.1/99.2)", "2026-09-29", "https://www.sec.gov/Archives/edgar/data/1899123/000121390026104638/ea030647301ex99-1.htm", "face debt, cash/restricted, shares incl. post-quarter issuance"),
 ("S-MARA-1", "MARA", "MARA Holdings 10-Q, quarter ended 2026-06-30 (Note 5, 6, 13, 17; MD&A energy capacity)", "2026-08-06", "https://www.sec.gov/Archives/edgar/data/1507605/000150760526000022/mara-20260630.htm", "balance sheet, debt, BTC, 1.9 GW, Aug-2026 facilities"),
 ("S-MARA-2", "MARA", "MARA Q2 2026 Shareholder Letter (8-K Ex.)", "2026-08-06", "https://www.sec.gov/Archives/edgar/data/1507605/000150760526000020/q226shareholderletter.htm", "Long Ridge 505 MW, 4.8 GW portfolio, Matagorda 2 GW"),
 ("S-CLSK-1", "CLSK", "CleanSpark 10-Q, quarter ended 2026-06-30 (fiscal Q3 2026)", "2026-08-06", "https://www.sec.gov/Archives/edgar/data/827876/000119312526338382/clsk-20260630.htm", "balance sheet, converts, shares"),
 ("S-CLSK-2", "CLSK", "CleanSpark 8-K — 7.875% Senior Secured Notes due 2031 (CSDC Finance I)", "2026-09-25", "https://www.sec.gov/Archives/edgar/data/827876/000119312526402944/clsk-20260925.htm", "PF debt $2,276m / est. net proceeds"),
 ("S-CLSK-3", "CLSK", "CleanSpark September 2026 Operational Update", "2026-10-09", "https://investors.cleanspark.com/news/news-details/2026/CleanSpark-Releases-September-2026-Operational-Update/default.aspx", "808 MW utilized, 1.8 GW contracted, 13,530 BTC, 50 EH/s, ERCOT designations"),
 ("S-IREN-1", "IREN", "IREN 10-K, fiscal year ended 2026-06-30 (Item 1 site table; Note 23 debt)", "2026-08-27", "https://www.sec.gov/Archives/edgar/data/1878848/000187884826000052/iren-20260630.htm", "balance sheet, face debt, site capacity 2,910 MW, ~5 GW, 380 MW mining"),
 ("S-IREN-2", "IREN", "IREN DEF 14A — shares outstanding 404,613,536 at 2026-09-28", "2026-10-13", "https://www.sec.gov/Archives/edgar/data/1878848/000114036126039451/ny20078226x1_def14a.htm", "basic shares"),
 ("S-IREN-3", "IREN", "IREN 8-K — Horizon 1 delivered to Microsoft; 480 MW gross AI Cloud 2026 / 1.2 GW 2027 targets", "2026-08-13", "https://www.sec.gov/Archives/edgar/data/1878848/000114036126032638/ef20080141_ex99-1.htm", "utilization note"),
 ("S-RIOT-1", "RIOT", "Riot Platforms 10-Q, quarter ended 2026-06-30 (MD&A developed capacity; Note 3, 5, 11)", "2026-08-10", "https://www.sec.gov/Archives/edgar/data/1167419/000110465926093448/riot-20260630x10q.htm", "balance sheet, debt, BTC, 1,292 MW developed, 241 IT MW leases"),
 ("S-RIOT-2", "RIOT", "Riot Platforms 8-K Item 1.02 — Coinbase facility prepaid and terminated 2026-09-21", "2026-09-25", "https://www.sec.gov/Archives/edgar/data/1167419/000110465926111003/riot-20260921x8k.htm", "PF debt/cash −$200m"),
 ("S-CORZ-1", "CORZ", "Core Scientific 10-Q, quarter ended 2026-06-30 (Note 2, 7, 8, 15; MD&A)", "2026-07-28", "https://www.sec.gov/Archives/edgar/data/1839341/000183934126000014/core-20260630.htm", "balance sheet, debt, BTC, leased/leasable IT MW"),
 ("S-CORZ-2", "CORZ", "Core Scientific Q2 2026 results release and earnings deck (8-K Ex. 99.1/99.2)", "2026-07-28", "https://www.sec.gov/Archives/edgar/data/1839341/000183934126000013/q22026corescientificinc-ea.htm", "437 MW billing, ~1.1 GW leased, ~1,540 MW leasable, AMD 2.5 GW"),
 ("S-CIFR-1", "CIFR", "Cipher Digital 10-Q, quarter ended 2026-06-30 (Note 1, 3, 14, 16; MD&A 5.3 GW)", "2026-08-04", "https://www.sec.gov/Archives/edgar/data/1819989/000181998926000041/cifr-20260630.htm", "balance sheet, project notes, BTC, Odessa 207 MW, portfolio"),
 ("S-CIFR-2", "CIFR", "Cipher Digital 8-K — pricing of $850m 0% converts 2032 and exchange of 2030 notes", "2026-10-14", "https://www.sec.gov/Archives/edgar/data/1819989/000119312526421035/d77312dex991.htm", "PF debt/cash/shares"),
 ("S-CIFR-3", "CIFR", "Cipher Digital — Project Compass investor presentation, October 2026 (8-K Ex. 99.1)", "2026-10-13", "https://www.sec.gov/Archives/edgar/data/1819989/000119312526419743/d134900dex991.htm", "907 MW operating + contracted, 700 MW gross HPC, pipeline"),
 ("S-HIVE-1", "HIVE", "HIVE Digital Technologies 10-Q, quarter ended 2026-06-30 (fiscal Q1 2027)", "2026-08-14", "https://www.sec.gov/Archives/edgar/data/1720424/000106299326004434/form10q.htm", "balance sheet, debt, BTC, site table"),
 ("S-HIVE-2", "HIVE", "HIVE fiscal Q1 2027 results release — ~440 MW operated, 540 MW after Yguazú +100 MW, Tier-III pipeline", "2026-08-15", "https://www.newsfilecorp.com/release/309810/HIVE-Reports-Q1-2027-Revenue-of-79.1-Million-Contracted-GPU-Cloud-ARR1-Reaches-Approximately-110-million", "D1/D2/D3"),
 ("S-HIVE-3", "HIVE", "Market-data aggregators (simplywall.st / equibles) — 267.43m shares outstanding, July 2026", "2026-07-30", "https://simplywall.st/stocks/ca/software/tsx-hive/hive-digital-technologies-shares/information", "basic shares (WARN: cover count not captured)"),
 ("S-WULF-1", "WULF", "TeraWulf 10-Q, quarter ended 2026-06-30 (Note 5, 10, 11; MD&A 145 MW mining / 81 MW HPC / 438 MW contracted)", "2026-08-05", "https://www.sec.gov/Archives/edgar/data/1083301/000108330126000166/wulf-20260630.htm", "balance sheet, face debt, BTC, in-service load"),
 ("S-WULF-2", "WULF", "TeraWulf Q2 2026 results release and investor presentation (8-K Ex. 99.1/99.2)", "2026-08-05", "https://www.sec.gov/Archives/edgar/data/1083301/000108330126000162/a_wulfearningsreleaseq22026.htm", "Lake Mariner 750 gross / 600 IT, 102 IT MW online, 336 under construction, Justified, Chesapeake"),
 ("S-WULF-3", "WULF", "TeraWulf 8-K — Muskie Data Campus contracted power increased to 1 GW", "2026-10-05", "https://www.sec.gov/Archives/edgar/data/1083301/000162828026064757/wulf-20261001.htm", "D3"),
 ("S-HUT-1", "HUT", "Hut 8 10-Q, quarter ended 2026-06-30 (Note 5, 9; MD&A energy capacity pipeline table)", "2026-08-04", "https://www.sec.gov/Archives/edgar/data/1964789/000110465926090025/hut-20260630x10q.htm", "balance sheet, project notes, BTC, 710 / 9,370 MW"),
 ("S-HUT-2", "HUT", "Hut 8 Q2 2026 results release (8-K Ex. 99.1) — 1,330 MW under construction, 949 IT MW contracted", "2026-08-04", "https://www.sec.gov/Archives/edgar/data/0001964789/000110465926090041/tm2621890d1_ex99-1.htm", "D2"),
 ("S-MKT", "all", "Equity closing prices 2026-10-15 — stockanalysis.com price history (Nasdaq); CLSK cross-checked on nasdaq.com", "2026-10-15", "https://stockanalysis.com/", "price"),
 ("S-BTC", "all", "CoinGecko BTC/USD 2026-10-15 20:00 UTC = 82,308.83 (same data cut as Mining NAV Standard v1.1)", "2026-10-15", "https://www.coingecko.com/en/coins/bitcoin", "BTC spot"),
 ("S-NAV", "all", "HASHFLOPS Mining NAV Standard v1.1 inputs (mining_nav_v1.1_inputs_2026-10-15.json) — shared balance-sheet data set", "2026-10-17", "project: claude/data/inputs/mining_nav_v1.1_inputs_2026-10-15.json", "cash, restricted cash, face debt, NCI, BTC, shares, PF events"),
]
for i, s in enumerate(SRC, start=5):
    for j, v in enumerate(s, start=1):
        c = SO.cell(i, j, v); c.font = F_N; c.alignment = WRAP
        if j == 5: c.hyperlink = v if v.startswith("http") else None; c.font = Font(name="Arial", size=9, color="0563C1", underline="single" if v.startswith("http") else None)
    SO.row_dimensions[i].height = 32
widths(SO, {"A": 11, "B": 7, "C": 70, "D": 11, "E": 60, "F": 40})
SO.freeze_panes = "A5"

# finance notes sheet (appendix) — one row per company
FN = wb.create_sheet("Balance_notes")
title(FN, "Balance-sheet notes — what is in debt, cash, NCI and BTC for each company", "Face debt composition, pro forma events and exclusions (leases, warrant liabilities, deferred revenue).", span=3)
hdr(FN, 4, ["Ticker", "Cohort", "Note"])
for i, c in enumerate(cc.COMPANIES):
    r = R0 + i
    FN.cell(r, 1, c["ticker"]).font = F_B; FN.cell(r, 2, c["cohort"]).alignment = Alignment(horizontal="center")
    FN.cell(r, 3, c["fin_note"]).font = F_N; FN.cell(r, 3).alignment = WRAP; FN.row_dimensions[r].height = 92
widths(FN, {"A": 8, "B": 8, "C": 150})

wb.save(OUT)
print("built", OUT)
