# -*- coding: utf-8 -*-
"""Independent (non-Excel) computation of every derived field in the Mining Companies Catalog v1.1.
Used by the builder for CSV/JSON exports and by the validator to compare against LibreOffice-recalculated cells."""
import datetime

def isnum(x):
    return isinstance(x, (int, float)) and not isinstance(x, bool)

def d(s):
    return datetime.date.fromisoformat(s) if isinstance(s, str) and len(s) == 10 and s[4] == '-' else None

def own_share(total, own, status):
    if status == 'REVIEW': return 'REVIEW'
    if not (isnum(total) and isnum(own)): return 'ND'
    if total <= 0: return 'NM'
    return own / total

def thematic_share_lb(total, own, host, equip, status):
    if status == 'REVIEW': return 'REVIEW'
    if not isnum(total): return 'ND'
    if total <= 0: return 'NM'
    comps = [x for x in (own, host, equip) if isnum(x)]
    if not comps: return 'ND'
    return sum(comps) / total

def tier(x):
    if not isnum(x): return x
    return 'CORE' if x >= 0.5 else ('SIGNIFICANT' if x >= 0.2 else 'PERIPHERAL')

def age_days(release, doc_date):
    a, b = d(release), d(doc_date)
    if a is None or b is None: return 'ND'
    return (a - b).days

def stale(age):
    if not isnum(age): return 'ND'
    return 'STALE' if age > 120 else 'OK'

def reg_share(mining_rev, total_rev, share_status):
    if share_status == 'REVIEW': return 'REVIEW'
    if not (isnum(mining_rev) and isnum(total_rev)): return 'ND'
    if total_rev <= 0: return 'NM'
    return mining_rev / total_rev

def market_cap(price, shares, ads, mcap_input):
    if isnum(price) and isnum(shares) and isnum(ads) and ads > 0:
        return price * shares / ads / 1e6
    if isnum(mcap_input): return mcap_input
    return 'ND'

def btc_after_pledge(total, date_total, pledged, date_pledge):
    if not (isnum(total) and isnum(pledged)): return 'ND'
    if date_total != date_pledge or pledged < 0 or pledged > total: return 'REVIEW'
    return total - pledged

def compute(data):
    """Return dict of derived values keyed exactly like the workbook cells the validator will read."""
    rel = data['release']['release_date']
    out = {'financials': [], 'catalog': [], 'register': [], 'operations': [], 'pledge': [], 'checks': {}, 'summary': {}}
    fin_by = {}
    for f in data['financials']:
        o = own_share(f['total'], f['own_mining'], f['status'])
        t = thematic_share_lb(f['total'], f['own_mining'], f['hosting_cloud'], f['equipment'], f['status'])
        a = age_days(rel, f['doc_date'])
        out['financials'].append({'own_share': o, 'thematic_share_lb': t, 'age_days': a, 'stale': stale(a)})
        fin_by[f['ticker']] = t
    for c in data['core']:
        t = fin_by.get(c['ticker'], 'ND')
        a = age_days(rel, c['doc_date'])
        out['catalog'].append({'thematic_share_lb': t, 'materiality_tier': tier(t), 'age_days': a, 'stale': stale(a)})
    for r in data['register']:
        out['register'].append({'mining_share': reg_share(r['mining_revenue'], r['total_revenue'], r['share_status']),
                                'market_cap_usd_m': market_cap(r['price_2026_10_15'], r['shares_basic'], r['ads_ratio'], r['market_cap_usd_m_input'])})
    for o in data['operations']:
        a = age_days(rel, o['doc_date'])
        out['operations'].append({'age_days': a, 'stale': stale(a)})
    for p in data['pledge']:
        out['pledge'].append({'after_pledge': btc_after_pledge(p['btc_total'], p['date_total'], p['pledged'], p['date_pledge'])})
    # ---- checks ----
    core = data['core']; ref = data['dc_reference']; rout = data['routing']; rev = data['review']; cand = data['candidates']; reg = data['register']
    ids = [c['issuer_id'] for c in core]; keys = [c['security_key'] for c in core]
    ref_keys = {r['security_key'] for r in ref}; ref_groups = {r['group_id'] for r in ref}; ref_names = {r['name_key'] for r in ref}; ref_tickers = {r['ticker'] for r in ref}
    rout_t = {r['ticker'] for r in rout}; rev_t = {r['ticker'] for r in rev}; cand_t = {r['ticker'] for r in cand}
    src_ids = {s['source_id'] for s in data['sources']}
    used_src = [c['source_id'] for c in core] + [f['source_id'] for f in data['financials']] + [o['source_id'] for o in data['operations']] + [r['source_id'] for r in rout] + [r['source_id'] for r in rev] + [r['source_id'] for r in reg if r['source_id']]
    former = []
    for c in core:
        former += [x for x in (c.get('former_tickers') or '').split(';') if x]
    ck = out['checks']
    ck['C01_dup_issuer_id'] = sum(1 for i in ids if ids.count(i) > 1)
    ck['C02_dup_security_key'] = sum(1 for k in keys if keys.count(k) > 1)
    ck['C03_core_security_in_dc_ref'] = sum(1 for k in keys if k in ref_keys)
    ck['C04_core_group_in_dc_ref'] = sum(1 for i in ids if i in ref_groups)
    ck['C05_core_namekey_in_dc_ref'] = sum(1 for c in core if c['name_key'] in ref_names)
    ck['C06_core_ticker_in_routing'] = sum(1 for c in core if c['ticker'] in rout_t)
    ck['C07_core_ticker_in_review'] = sum(1 for c in core if c['ticker'] in rev_t)
    ck['C08_core_ticker_in_candidates'] = sum(1 for c in core if c['ticker'] in cand_t)
    ck['C09_former_tickers_in_dc_ref'] = sum(1 for t in former if t in ref_tickers)
    ck['C10_missing_source_ids'] = sum(1 for s in used_src if s not in src_ids)
    ck['C11_doc_dates_after_release'] = sum(1 for c in core if d(c['doc_date']) and d(c['doc_date']) > d(rel))
    ck['C12_pending_deadline_before_release'] = sum(1 for r in rout if r.get('pending_deadline') and d(r['pending_deadline']) < d(rel))
    ck['C13_existing_routing_not_in_dc_ref'] = sum(1 for r in rout if r['status'] == 'EXISTING_DC_AI' and r['group_id'] not in ref_groups)
    prim = [r['group_id'] for r in reg if r['status'] not in ('CONTROLLED_CHILD', 'PARENT_REFERENCE')]
    ck['C14_dup_primary_register_group'] = sum(1 for g in prim if prim.count(g) > 1)
    ck['C15_bad_financial_status'] = sum(1 for f in data['financials'] if f['status'] not in ('VALUE', 'ND', 'REVIEW', 'NP'))
    ck['C16_register_rows_without_core_or_routing'] = sum(1 for r in reg if r['ticker'] not in {c['ticker'] for c in core} | rout_t)
    ck['I01_stale_financial_rows'] = sum(1 for x in out['financials'] if x['stale'] == 'STALE')
    ck['I02_register_with_market_cap'] = sum(1 for x in out['register'] if isnum(x['market_cap_usd_m']))
    ck['I03_register_with_share_value'] = sum(1 for x in out['register'] if isnum(x['mining_share']))
    # ---- summary ----
    sm = out['summary']
    sm['core_total'] = len(core)
    for s in ('M1', 'M2', 'M3'): sm[f'core_{s}'] = sum(1 for c in core if c['segment'] == s)
    for s in ('EXISTING_DC_AI', 'PARENT_REFERENCE', 'CONTROLLED_CHILD', 'PENDING_DC_AI'): sm[f'routing_{s}'] = sum(1 for r in rout if r['status'] == s)
    sm['review'] = len(rev); sm['candidates'] = len(cand); sm['register'] = len(reg); sm['dc_reference'] = len(ref); sm['sources'] = len(data['sources'])
    sm['register_mcap_sum_usd_m'] = sum(x['market_cap_usd_m'] for x in out['register'] if isnum(x['market_cap_usd_m']))
    sm['core_mcap_sum_usd_m'] = sum(x['market_cap_usd_m'] for x, r in zip(out['register'], reg) if isnum(x['market_cap_usd_m']) and r['owner_catalog'] == 'MINING')
    sm['core_mcap_count'] = sum(1 for x, r in zip(out['register'], reg) if isnum(x['market_cap_usd_m']) and r['owner_catalog'] == 'MINING')
    sm['core_share_value'] = sum(1 for x in out['financials'] if isnum(x['own_share']))
    return out
