# -*- coding: utf-8 -*-
"""Render the English publication page (Public Summary) for hashflops.io from catalog_data.json + engine results + validation stamp."""
import json, os, sys, hashlib
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import engine_v1_1 as E
HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.join(HERE, '..'); REPRO = os.path.join(ROOT, 'repro'); REL = os.path.join(ROOT, 'release')
D = json.load(open(os.path.join(REPRO, 'catalog_data.json'), encoding='utf-8'))
ST = json.load(open(os.path.join(REPRO, 'validation_stamp.json')))
FP = hashlib.sha256(json.dumps(D, ensure_ascii=False, sort_keys=True, indent=1).encode('utf-8')).hexdigest()
DER = E.compute(D); R = D['release']; sm = DER['summary']

def pct(x): return f"{x*100:.1f}%" if E.isnum(x) else str(x)
def num(x, d=0): return (f"{x:,.{d}f}" if E.isnum(x) else str(x))
def usd_m(x): return f"${x:,.0f}m" if E.isnum(x) else 'ND'
def esc(s): return str(s).replace('|', '／')

core = list(zip(D['core'], DER['catalog'])); fin = {f['ticker']: (f, dv) for f, dv in zip(D['financials'], DER['financials'])}
reg = {r['ticker']: (r, dv) for r, dv in zip(D['register'], DER['register'])}
src = {s['source_id']: s for s in D['sources']}

L = []
L.append(f"# Public Mining Companies — Catalog v{R['version']}")
L.append(f"*{R['catalog_name']} v{R['version']} · composition {R['composition_date']} · data cut: {R['data_cut']} · published {R['release_date']}*")
L.append('')
L.append('## Headline')
L.append(f"- **{sm['core_total']} economic groups in the mining core** (M1 own mining {sm['core_M1']} · M2 mining services {sm['core_M2']} · M3 equipment {sm['core_M3']}), one listed security each; owner = this catalog. Two additions since v1.0: Cango (CANG) and PowerCompute (PWCM, ex-LM Funding).")
L.append(f"- **{sm['routing_EXISTING_DC_AI']} groups with a mining relation are owned by the DC/AI catalog** (IREN, HIVE, CORZ, WULF, APLD, HUT, CIFR, BTDR, WYFI, GLXY) and **{sm['routing_PENDING_DC_AI']} are pending a DC/AI decision** (MARA, RIOT, CLSK, DGXX, DMGI, AGMH, QMLS; deadline 2026-11-30, rule R21). They are not members here but are tracked in the **mining exposure register** below.")
reg_mcap = sm['register_mcap_sum_usd_m']; core_mcap = sm['core_mcap_sum_usd_m']
L.append(f"- The register covers **{sm['register']} securities / 32 groups**; market capitalisation is available for {DER['checks']['I02_register_with_market_cap']} of them (close 2026-10-15): **{usd_m(reg_mcap)}** in total, of which the mining core (8 covered members) is **{usd_m(core_mcap)}** — about {core_mcap/reg_mcap*100:.0f}%. The investable part of listed mining sits with hybrids owned by, or pending for, the DC/AI catalog.")
L.append(f"- Keel Infrastructure (ex-Bitfarms) stays in the core on actual Q2 2026 production (354 BTC, Québec only) but is flagged **WIND_DOWN_ANNOUNCED**; it is re-reviewed at the Q3 2026 10-Q.")
L.append(f"- Release control: {ST['checks'].split(';')[0]}; LibreOffice recalc {ST['libreoffice_recalc']}; engine compare {ST['engine_compare']}; verdict **{ST['verdict']}**.")
L.append('')
L.append('## Core composition (owner MINING)')
L.append('| # | Company | Ticker | Seg. | Business model | Mining status | AI/HPC stage | Thematic share (lower bound) | Tier (R25) | Market cap 2026-10-15 | Basis (period) |')
L.append('|---|---|---|---|---|---|---|---:|---|---:|---|')
for i, (c, dv) in enumerate(core, 1):
    f, fdv = fin[c['ticker']]
    L.append(f"| {i} | {esc(c['company'])} | {c['ticker']}:{c['mic']} | {c['segment']} | {c['business_model']}{(' · ' + c['tags'].replace(';', ', ')) if c['tags'] else ''} | {c['mining_status']} | {c['ai_hpc_stage']} | {pct(dv['thematic_share_lb'])} | {dv['materiality_tier']} | {usd_m(c['market_cap_usd_m'])} | {f['period']} |")
L.append('')
L.append('Thematic share = (own mining + hosting/cloud + equipment revenue) ÷ total revenue in the same period, currency and perimeter; ND components are not estimated, so the figure is a lower bound. REVIEW = conflicting disclosures (SOS: FY2025 total revenue differs between table and narrative; VIP: the Q2 2026 total excludes wholesale power sales). Tiers are informational in v1.1 and do not change membership.')
L.append('')
L.append('### Admission basis and risk notes')
for c, dv in core:
    L.append(f"- **{c['company']} ({c['ticker']})** — {c['admission_basis']} *Risks:* {c['risks_notes']}" + (f" *Formerly:* {c['former_identifiers']}." if c['former_identifiers'] else ''))
L.append('')
L.append('## DC/AI boundary — groups with a mining relation that are not members')
L.append('| Ticker | Company | Status | DC/AI group | Segment | Mining relation | AI/HPC stage | Mining share Q2 2026 | Note |')
L.append('|---|---|---|---|---|---|---|---:|---|')
for x in D['routing']:
    r, rdv = reg.get(x['ticker'], (None, None))
    share = pct(rdv['mining_share']) if rdv else 'ND'
    L.append(f"| {x['ticker']} | {esc(x['company'])} | {x['status']} | {x['group_id']} | {x['dc_segment']} | {x['mining_relation']} | {x['ai_hpc_stage']} | {share} | {esc(x['action'])} |")
L.append('')
L.append('Rule R21 (new in v1.1): a transfer proposal may stay pending for at most one DC/AI refresh cycle. The seven PENDING groups were proposed on 2026-10-08; if the DC/AI catalog has not admitted them by 2026-11-30 they return to the mining core with tag AI_PENDING. Rule R24 (proposal, not applied): American Bitcoin (ABTC), a listed consolidated subsidiary of Hut 8 whose own revenue is 100% mining, could be admitted as CHILD_OF_DC_AI with a free-float adjustment — decision deferred to v1.2.')
L.append('')
L.append('## Mining exposure register — all listed groups with PoW-mining exposure (whatever the owner)')
L.append('| Group | Ticker | Owner | Status | Mining status | BTC mined Q2 2026 | Mining rev. share Q2 2026 | Share TTM (4Q) | Hashrate EH/s (op. / inst.) | Power MW | BTC held (date) | Market cap USD m (2026-10-15) | Cost Std tier |')
L.append('|---|---|---|---|---|---:|---:|---:|---|---:|---|---:|---|')
order = sorted(zip(D['register'], DER['register']), key=lambda t: (-(t[1]['market_cap_usd_m']) if E.isnum(t[1]['market_cap_usd_m']) else 1e9))
for r, dv in order:
    ttm = pct(r['mining_share_ttm']) + (f" ({r['ttm_quarters']}Q)" if E.isnum(r['mining_share_ttm']) and r['ttm_quarters'] and r['ttm_quarters'] != 4 else '')
    hr = f"{num(r['hashrate_eh_operating'],2) if E.isnum(r['hashrate_eh_operating']) else 'ND'} / {num(r['hashrate_eh_installed'],2) if E.isnum(r['hashrate_eh_installed']) else 'ND'}"
    held = f"{num(r['btc_held'],1 if E.isnum(r['btc_held']) and r['btc_held']%1 else 0)} ({r['btc_held_date']})" if E.isnum(r['btc_held']) else 'ND'
    mc = num(dv['market_cap_usd_m'], 1) if E.isnum(dv['market_cap_usd_m']) else 'ND'
    if E.isnum(dv['market_cap_usd_m']) and r['market_cap_date'] != '2026-10-15': mc += f" ({r['market_cap_date']})"
    L.append(f"| {r['group_id']} | {r['ticker']} | {r['owner_catalog']} | {r['status']} | {r['mining_status']} | {num(r['btc_mined_q2_2026'],1 if E.isnum(r['btc_mined_q2_2026']) and r['btc_mined_q2_2026']%1 else 0)} | {pct(dv['mining_share'])} | {ttm} | {hr} | {num(r['power_mw'],1 if E.isnum(r['power_mw']) and r['power_mw']%1 else 0)} | {held} | {mc} | {r['cost_standard_tier']} |")
L.append('')
L.append('Mining-revenue share for the 15 companies covered by the Mining Cost Standard v1.0 = BTC-mining segment revenue ÷ total revenue from XBRL facts (Q2 2026; TTM = Σ four quarters). Other rows use the catalog\'s own financial observations (own-mining revenue; period as labelled) or DC/AI catalog 1.2 disclosures (APLD mining hosting; WYFI and GLXY never/no longer mine). Hashrate definitions differ by issuer (average operating vs deployed vs installed vs under management) and are not harmonised. Market caps = closing price 2026-10-15 × basic shares outstanding from the latest filing (ADS ratio applied for ARBK); APLD, WYFI and GLXY from the DC/AI 1.2 snapshot (dates shown). HUT\'s share includes consolidated ABTC. BTBT and ABTC are reference securities of groups DC098 and DC083 (not counted as separate groups).')
L.append('')
L.append('## REVIEW queue and candidates')
L.append('| Ticker | Company | Status | Why | What would resolve it |'); L.append('|---|---|---|---|---|')
for x in D['review']:
    L.append(f"| {x['ticker']} | {esc(x['company'])}{(' (ex-' + esc(x['former_identifiers']) + ')') if x['former_identifiers'] else ''} | REVIEW | {esc(x['reason'])} | {esc(x['to_confirm'])} |")
for x in D['candidates']:
    L.append(f"| {x['ticker']} | {esc(x['company'])} ({x['exchange']}) | CANDIDATE — {x['route']} | not assessed | {esc(x['evidence_needed'])} |")
L.append('')
L.append('Outside scope by construction: private miners and vendors (Bitmain, MicroBT, Foundry, Luxor, Antpool, F2Pool, ViaBTC), diversified groups whose mining line is not a primary product (Block/Proto), and the crypto sector at large (exchanges, custodians, treasuries, PoS staking).')
L.append('')
L.append('## How the catalog is built')
L.append('1. **Scope and admission (R01–R05).** Listed companies with an *operating* PoW-mining, mining-services or mining-equipment business, evidenced by a primary source (SEC/SEDAR filing or official release): actual production, recognized thematic revenue, current shipments or an operating customer service. Land, LOIs, MoUs, pipeline MW and AI marketing are ANNOUNCED and change nothing.')
L.append('2. **DC/AI priority and one owner per group (R03, R06, R16, R21).** A group with a qualifying commercial DC/AI business (operating service or binding customer contract) belongs to the DC/AI Public Companies Catalog (1.2, 111 issuers) and appears here only in the boundary registry and the exposure register. Controlled subsidiaries, ADRs and dual listings never create a second member. Pending transfers expire after one cycle.')
L.append('3. **Segments (R07–R09, R23).** M1 own PoW mining (hashpower sold through a marketplace from own machines is M1 with tag HASHRATE_MARKETPLACE); M2 hosting, co-mining, cloud mining, hashrate contracts; M3 ASIC design, equipment supply and resale. The primary product defines the segment; a single quarter does not reclassify.')
L.append('4. **Data discipline (R10–R14, R26).** VALUE / ND / NP / NM / REVIEW statuses; same period, currency and perimeter for every ratio; own, customer, JV and BTC-equivalent production kept apart; installed, managed and average hashrate kept apart; BTC balances with date and pledge; observation age with a 120-day STALE flag.')
L.append('5. **Mining status and materiality (R22, R25).** ACTIVE / WIND_DOWN_ANNOUNCED / SUSPENDED / RESIDUAL / EXITED from the latest filing; materiality tiers from the thematic revenue share (CORE ≥ 50%, SIGNIFICANT 20–50%, PERIPHERAL < 20%) — published, not yet used for membership.')
L.append('6. **Release control (R15).** Uniqueness of group and security; anti-join with the DC/AI reference by security, normalised name and former identifiers; routing, review and candidates must not overlap the core; every number links to a source id; pending deadlines in the future; one primary register row per group. 16 blocking checks are formulas in the workbook and are recomputed by an independent Python engine.')
L.append('7. **Verification.** LibreOffice headless recalculation (zero formula errors) → Python engine recomputes every derived cell (shares, tiers, ages, market caps, checks, summary counters) without executing Excel formulas → results stamped into the workbook and this page.')
L.append('')
L.append('## Changes since v1.0 (2026-10-08)')
for x in D['change_log']:
    L.append(f"- **{x['area']} · {x['item']} · {x['change']}** — {x['details']}")
L.append('')
L.append('## Known limitations')
L.append('- Completeness is not claimed: 12 candidates are unassessed (see register); non-US listings (TSXV, ADX, LSE, Xetra) are covered only where a primary source was reviewed.')
L.append('- Own-mining revenue share is comparable for 8 of 15 core members; PHX, SATO, DTCX, DRK and PWCM do not disclose a usable split; VIP and SOS are blocked (REVIEW).')
L.append('- Operational coverage is uneven: OLB has no operational observation; hashrate is available for 7 core members; hashrate definitions are issuer-specific.')
L.append('- Market data is a 2026-10-15 snapshot for 24 of 34 register rows; the catalog is not a valuation model and carries no multiples.')
L.append('- The seven PENDING groups and ABTC (child of HUT) are the main reason the core looks small: by construction, any miner with a binding AI/HPC contract or operating AI service migrates to the DC/AI catalog. Anyone building a "listed miners" universe should start from the exposure register, not from the core alone.')
L.append('- Two financial rows are older than 120 days (ARBK FY2025 20-F; SOS FY2025 20-F) and are flagged STALE.')
L.append('')
L.append('## Model integrity')
for k, v in [('Catalog version', R['version']), ('Composition date', R['composition_date']), ('Data cut', R['data_cut']), ('DC/AI reference', f"catalog {R['dc_ai_reference']['version']} of {R['dc_ai_reference']['date']} ({R['dc_ai_reference']['issuers']} issuers)"),
             ('Core / routing / review / candidates / register', f"{sm['core_total']} / {len(D['routing'])} / {sm['review']} / {sm['candidates']} / {sm['register']}"),
             ('LibreOffice recalc', ST['libreoffice_recalc']), ('Engine compare', ST['engine_compare']), ('Checks', ST['checks']), ('Verdict', ST['verdict']), ('Validated at (UTC)', ST['validated_at_utc']),
             ('Inputs fingerprint (SHA-256 catalog_data.json)', f"`{FP}`"), ('Upstream: Mining Cost Standard v1.0 (2026Q2)', f"`{R['upstream']['cost_standard']['fingerprint']}`"), ('Upstream: Mining NAV Standard v1.1 (2026-10-15)', f"`{R['upstream']['nav_standard']['fingerprint']}`")]:
    L.append(f"- **{k}:** {v}")
L.append('')
L.append('## Sources')
L.append('Every decision and number in the workbook carries a source id. Primary filings behind the v1.1 additions and the register:')
L.append('| Id | Document | Date | Provenance |'); L.append('|---|---|---|---|')
for s in D['sources']:
    if s['added_in_version'] == '1.1' or s['source_id'] in ('S001', 'S002', 'S003', 'S004', 'S005', 'S006', 'S007', 'S008', 'S009', 'S010', 'S011', 'S012', 'S013'):
        L.append(f"| {s['source_id']} | [{esc(s['document'])}]({s['url']}) | {s['doc_date']} | {esc(s['provenance'])} |")
L.append('')
L.append('Full registry (62 entries, incl. the inherited DC/AI classification sources S018–S038): Sources sheet of the workbook / `mining_catalog_v1.1_sources_2026-10-17.csv`.')
L.append('')
L.append('## Downloads')
L.append('- `Mining_Catalog_v1.1_2026-10-17.xlsx` — workbook (Public_Summary, Version_Log, Catalog, Financials, Operations, Routing, Review, Candidates, Exposure_Register, DC_AI_Reference, Rules, Sources, Change_Log, Checks).')
L.append('- CSV: core, financials, operations, routing, review, candidates, exposure register, DC/AI reference, sources, rules; JSON: `mining_catalog_v1.1_2026-10-17.json` (inputs + derived values + fingerprint).')
L.append('- `Mining_Catalog_v1.1_repro.zip` — catalog_data.json, build / engine / validation scripts, v1.0 workbook dump, upstream input extract, validation log.')
L.append('')
L.append('## Disclaimer')
L.append('1. Informational research; not investment advice, not an offer or solicitation; no recommendations, target prices or signals are made or implied.')
L.append("2. Composition and classifications follow the published rules applied to issuers' filings; they are model outputs and may differ from other providers' sector definitions. Membership is not an endorsement; exclusion is not a judgement on quality.")
L.append('3. Sources are cited per decision and per number; the base is revised when issuers restate or when errors are found (errata with the next release; prior versions retained).')
L.append('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.')
L.append('5. Readers are encouraged to reproduce the composition and the release checks from the reproducibility package.')
out = os.path.join(REL, 'Mining_Catalog_v1.1_2026-10-17_Public_Summary_EN.md')
open(out, 'w', encoding='utf-8').write('\n'.join(L) + '\n')
print('written', out, len('\n'.join(L)), 'chars')
