# -*- coding: utf-8 -*-
"""Build the CAIDC publication data package (English, machine-readable) from the frozen pre-registered run, the forward roll
and the refreshed research re-run. Usage: python -I build_public_package.py <frozen_results> <forward_dir> <rerun_results> <root_new> <root_frozen> <out_dir>"""
import sys, json, hashlib, datetime as dt
from pathlib import Path
import numpy as np, pandas as pd

FZ, FW, RR, ROOT, ROOTF, OUT = [Path(a) for a in sys.argv[1:7]]; OUT.mkdir(parents=True, exist_ok=True)
R = json.loads((ROOT / 'rules_v0_4.json').read_text(encoding='utf-8')); U = json.loads((ROOT / 'universe_v0_3.json').read_text(encoding='utf-8')); SEC = {s['symbol']: s for s in U['securities']}
S = json.loads((FZ / 'summary.json').read_text(encoding='utf-8')); PRE = json.loads((FZ / 'pre_registration_v0_4.json').read_text(encoding='utf-8')); META = json.loads((FW / 'forward_meta.json').read_text(encoding='utf-8'))
SR = json.loads((RR / 'summary.json').read_text(encoding='utf-8')) if (RR / 'summary.json').exists() else None
V = 'V04_EXPW_ext'; IDX = R['index']; BASE_DATE = pd.Timestamp(IDX['base_date']); PUB_DATE = '2026-10-17'; FIRST_LIVE = pd.Timestamp('2026-10-12')
SEGN = {'S1': 'Power', 'S2': 'Thermal & Electrical Systems', 'S3': 'Connectivity', 'S4': 'Compute', 'S5': 'Capacity'}
BASIS = lambda s: ('DISCLOSED' if SEC[s]['origin'] == 'catalog_84' and 'раскры' in (SEC[s].get('exposure_basis') or '') else ('PURE_PLAY' if SEC[s]['exposure_mid'] == 1.0 else ('ANALYST_ESTIMATE' if SEC[s]['origin'] != 'catalog_84' else 'SEGMENT_REPORTING_ESTIMATE')))

# ---------------------------------------------------------------- levels
G = pd.read_csv(FW / f'{V}_daily_stitched.csv', index_col=0, parse_dates=True); P = pd.read_csv(FW / f'{V}_PR_daily_stitched.csv', index_col=0, parse_dates=True)
LV = pd.read_csv(FZ / 'levels_common.csv', index_col=0, parse_dates=True)
# benchmarks: frozen common levels through 10-09, extended with new prices (rebased continuity)
def load_close(sym):
    o = json.loads((ROOT / 'raw' / f'{sym}.json').read_text())['chart']['result'][0]; tz = o['meta'].get('exchangeTimezoneName', 'UTC')
    idx = pd.to_datetime(o['timestamp'], unit='s', utc=True).tz_convert(tz).tz_localize(None).normalize(); return pd.Series(o['indicators']['adjclose'][0]['adjclose'], index=idx).dropna()
bench = {}
for b in ['QQQ', 'SPY', 'ACWI']:
    adj = load_close(b).reindex(G.index).ffill(); bench[b] = adj / adj.iloc[0] * 1000.0
B = pd.DataFrame(bench)
out = pd.DataFrame({'date': G.index.strftime('%Y-%m-%d'), 'CAIDCG_research_gross_TR': G.gross_level.values, 'CAIDCN_research_net_of_model_costs': G.net_level.values, 'CAIDCP_research_price_return': P.gross_level.values,
                    'QQQ_TR_rebased': B['QQQ'].values, 'SPY_TR_rebased': B['SPY'].values, 'ACWI_TR_rebased': B['ACWI'].values}).set_index('date')
base_ix = G.index.get_indexer([BASE_DATE])[0]
for col, src in [('CAIDCG_official', G.gross_level), ('CAIDCP_official', P.gross_level), ('CAIDCN_official', G.net_level)]:
    v = src / src.iloc[base_ix] * IDX['base_level']; v[G.index < BASE_DATE] = np.nan; out[col] = v.values
out['series_status'] = np.where(G.index < FIRST_LIVE, 'BACKTEST_HYPOTHETICAL', 'LIVE_CALCULATION')
out.round(6).to_csv(OUT / 'caidc_levels_daily.csv')

# ---------------------------------------------------------------- constituents & history
Wf = pd.read_csv(FW / f'{V}_forward_weights.csv', index_col=0, parse_dates=True).iloc[-1]; comp = pd.read_csv(FZ / f'{V}_composition.csv', parse_dates=['rebalance_date'])
last_rb = comp.rebalance_date.max(); tgt = comp[comp.rebalance_date == last_rb].set_index('symbol')
cur = pd.read_csv(FZ / 'current_composition_main.csv').set_index('symbol'); el = pd.read_csv(FZ / f'{V}_eligibility.csv'); el_last = el[el.selection_date == el.selection_date.max()].set_index('symbol')
rows = []
for s in tgt.index:
    x = SEC[s]; rows.append(dict(symbol=s, ticker=x['ticker'], mic=x['mic'], name=x['name'], country=x['domicile'], quote_currency=x['quote_currency'], segment=x['segment_v03'], segment_name=SEGN[x['segment_v03']], group='CORE' if x['coverage_group'] == 'CORE' else 'G_SLEEVE',
                     stage=tgt.at[s, 'stage'], weight_2026_10_16=float(Wf[s]), target_weight_2026_09_30=float(tgt.at[s, 'target_weight']), exposure_low=x['exposure_low'], exposure_high=x['exposure_high'], exposure_mid=x['exposure_mid'], exposure_class=x['exposure_class'], exposure_basis_type=BASIS(s),
                     cap_proxy_usd_bn_2026_10_09=cur.at[s, 'cap_proxy_usd_bn'] if s in cur.index else np.nan, median_adv60_usd_mn_2026_10_09=cur.at[s, 'median_adv60_usd_mn'] if s in cur.index else np.nan, days_to_build_1bn_at_10pct=cur.at[s, 'days_to_build_1bn'] if s in cur.index else np.nan, universe_origin=x['origin']))
CON = pd.DataFrame(rows).sort_values('weight_2026_10_16', ascending=False); CON.round(6).to_csv(OUT / 'caidc_constituents_2026-10-16.csv', index=False)
comp.assign(segment_name=comp.segment.map(SEGN))[['rebalance_date', 'symbol', 'segment', 'segment_name', 'group', 'stage', 'target_weight', 'exposure_mid']].to_csv(OUT / 'caidc_composition_history.csv', index=False)
pt = pd.read_csv(FZ / f'{V}_purity_ts.csv'); pt.to_csv(OUT / 'caidc_purity_series.csv', index=False)
el_pub = el[el.selection_date == el.selection_date.max()][['selection_date', 'symbol', 'segment', 'group', 'median_adv60_usd', 'cap_proxy_usd', 'free_float', 'exposure_mid', 'stage', 'eligible', 'reasons', 'selected', 'rank_in_segment']]
el_pub.to_csv(OUT / 'caidc_eligibility_2026-05-29.csv', index=False)

# ---------------------------------------------------------------- calendar returns
def calret(series, freq):
    s = series.resample(freq).last(); first = series.iloc[0]
    r = s.pct_change(); r.iloc[0] = s.iloc[0] / first - 1; return r
cal_rows = []
for nm, ser in [('CAIDCG', G.gross_level), ('CAIDCN', G.net_level), ('CAIDCP', P.gross_level), ('QQQ', B['QQQ']), ('SPY', B['SPY']), ('ACWI', B['ACWI'])]:
    y = calret(ser, 'YE'); m = calret(ser, 'ME')
    for d, v in y.items(): cal_rows.append(dict(period_type='year', period=str(d.year), series=nm, ret=v, partial=d.year in (G.index[0].year, G.index[-1].year)))
    for d, v in m.items(): cal_rows.append(dict(period_type='month', period=d.strftime('%Y-%m'), series=nm, ret=v, partial=d.strftime('%Y-%m') in (G.index[0].strftime('%Y-%m'), G.index[-1].strftime('%Y-%m'))))
pd.DataFrame(cal_rows).round(6).to_csv(OUT / 'caidc_returns_calendar.csv', index=False)

# ---------------------------------------------------------------- factsheet
def perf(ser, end, start):
    s = ser.loc[:end]; a = s[s.index <= start]
    return float(s.iloc[-1] / a.iloc[-1] - 1) if len(a) else None
end = G.index[-1]
def stats(ser, start=None):
    s = ser if start is None else ser.loc[start:]; r = s.pct_change().dropna(); yrs = (s.index[-1] - s.index[0]).days / 365.25
    return dict(cagr=float((s.iloc[-1] / s.iloc[0]) ** (1 / yrs) - 1), volatility=float(r.std(ddof=1) * np.sqrt(252)), max_drawdown=float((s / s.cummax() - 1).min()), years=round(yrs, 3))
windows = {'1w': end - pd.Timedelta(days=7), '1m': end - pd.DateOffset(months=1), '3m': end - pd.DateOffset(months=3), 'ytd': pd.Timestamp(f'{end.year - 1}-12-31'), '1y': end - pd.DateOffset(years=1), '3y': end - pd.DateOffset(years=3), '5y': end - pd.DateOffset(years=5), 'since_base_2025-06-30': BASE_DATE, 'since_2015-06-30': G.index[0]}
perf_tab = {k: {nm: perf(ser, end, d) for nm, ser in [('CAIDCG', G.gross_level), ('CAIDCN', G.net_level), ('CAIDCP', P.gross_level), ('QQQ', B['QQQ']), ('SPY', B['SPY']), ('ACWI', B['ACWI'])]} for k, d in windows.items()}
seg_w = CON.groupby('segment').weight_2026_10_16.sum().round(6).to_dict(); ctry = CON.groupby('country').weight_2026_10_16.sum().sort_values(ascending=False).round(6).to_dict()
pur = CON.assign(we=CON.weight_2026_10_16 * CON.exposure_mid.fillna(0)); purity_now = float(pur.we.sum() / pur.weight_2026_10_16.sum()); pur_seg = (pur.groupby('segment').we.sum() / pur.groupby('segment').weight_2026_10_16.sum()).round(4).to_dict()
fact = dict(index=dict(name=IDX['name_en'], name_ru=IDX['name_ru'], code=IDX['code'], family=IDX['family'], provider=IDX['provider'], tagline=IDX['tagline_en'], former_name=IDX['former_name'], methodology_version='v0.4', rules_version=R['rules_version'], rules_date=R['rules_date'], status='RESEARCH_INDEX_NOT_A_LICENSED_BENCHMARK',
                       base_date=IDX['base_date'], base_level=IDX['base_level'], first_live_calculation_date=str(FIRST_LIVE.date()), backtest_period=f"{G.index[0].date()} – 2026-10-09 (hypothetical, pre-registered run)", series=dict(CAIDCG='gross total return (gross dividends reinvested)', CAIDCP='price return', CAIDCN='research net series: CAIDCG less a hypothetical fund-cost overlay (0.6% p.a. + 15 bp per dollar traded) — not an index net-of-withholding-tax series')),
            data_cut=dict(prices_through=str(end.date()), fx='ECB reference rates 14:15 CET same day (10 currencies); TWD via Yahoo previous bar', prices_source='Yahoo Finance daily bars (adjusted close, dividends, splits) — research snapshot, not licensed exchange data', shares='SEC EDGAR XBRL point-in-time for 79 US-listed securities; latest reported count for 48 others', published=PUB_DATE, next_rebalance='2026-12-31', next_selection='2027-05-31 (effective 2027-06-30)'),
            levels=dict(date=str(end.date()), CAIDCG_official=float(out['CAIDCG_official'].iloc[-1]), CAIDCP_official=float(out['CAIDCP_official'].iloc[-1]), CAIDCN_official=float(out['CAIDCN_official'].iloc[-1]), CAIDCG_research=float(G.gross_level.iloc[-1]), CAIDCP_research=float(P.gross_level.iloc[-1]), CAIDCN_research=float(G.net_level.iloc[-1])),
            performance=perf_tab, risk_research_2015_2026=dict(CAIDCG=stats(G.gross_level), CAIDCN=stats(G.net_level), CAIDCP=stats(P.gross_level), QQQ=stats(B['QQQ']), SPY=stats(B['SPY'])), risk_since_base=dict(CAIDCG=stats(G.gross_level, BASE_DATE), QQQ=stats(B['QQQ'], BASE_DATE)),
            composition=dict(as_of=str(end.date()), last_rebalance=str(last_rb.date()), members=int(len(CON)), hhi=float((CON.weight_2026_10_16 ** 2).sum()), cash=float(META['cash_end']), segment_weights=seg_w, country_weights=ctry, top10=CON.head(10)[['symbol', 'name', 'segment', 'weight_2026_10_16']].round(4).to_dict('records'), purity_weighted_exposure=purity_now, purity_by_segment=pur_seg, purity_latest_rebalance=float(pt.purity.iloc[-1]), purity_rated_latest_rebalance=float(pt.purity_rated.iloc[-1]) if 'purity_rated' in pt else None, unrated_weight=float(pt.unrated_weight.iloc[-1]) if 'unrated_weight' in pt else None),
            research_statistics=dict(bootstrap_90pct_ci=S['statistical_robustness']['bootstrap_ci'], deflated_sharpe=S['statistical_robustness']['deflated_sharpe'], factor_style=S['factor_regression']['style_nonneg_sum1'], factor_ols=S['factor_regression']['ols'], impact_cost=S['impact_cost']),
            integrity=dict(pre_registration_combined_sha256=PRE['combined_sha256'], frozen_run_input_sha256=S['input_sha256'], refreshed_snapshot_sha256=META['input_sha256'], engine_version=S['engine_version'], forward_calculator='caidc_forward.py (drift of frozen 2026-10-09 weights, no rebalance in window)'))
(OUT / 'caidc_factsheet.json').write_text(json.dumps(fact, ensure_ascii=False, indent=1, default=str), encoding='utf-8')

# ---------------------------------------------------------------- validation log
val = dict(published=PUB_DATE, frozen_run=dict(variants=list(S['validation'].keys()), all_pass=all(v['status'] == 'PASS' for v in S['validation'].values()), tests=S['tests'], workbook=json.loads((FZ / 'workbook_validation.json').read_text(encoding='utf-8')) if (FZ / 'workbook_validation.json').exists() else None),
           forward_roll=dict(sessions=META['sessions_added'], period_return_gross=META['period_return_gross'], period_return_pr=META['period_return_pr'], bench=META['bench_period'], weights_sum_end=float(Wf.sum())))
if SR is not None:
    a = pd.read_csv(FZ / f'{V}_daily.csv', index_col=0, parse_dates=True); b = pd.read_csv(RR / f'{V}_daily.csv', index_col=0, parse_dates=True); j = a.join(b, lsuffix='_f', rsuffix='_n', how='inner')
    ca = pd.read_csv(FZ / f'{V}_composition.csv'); cb = pd.read_csv(RR / f'{V}_composition.csv'); m = ca.merge(cb, on=['rebalance_date', 'symbol'], how='outer', suffixes=('_f', '_n'), indicator=True)
    val['rerun_on_refreshed_snapshot'] = dict(all_pass=all(v['status'] == 'PASS' for v in SR['validation'].values()), max_abs_diff_daily_gross_return_through_2026_10_09=float((j.gross_return_f - j.gross_return_n).abs().max()), composition_rows_frozen=int(len(ca)), composition_rows_rerun=int(len(cb)), composition_rows_matched=int((m._merge == 'both').sum()), max_abs_diff_target_weight=float((m.target_weight_f - m.target_weight_n).abs().max()),
                                              level_2026_10_16_rerun_gross=float(b.gross_level.iloc[-1]), level_2026_10_16_forward_gross=float(G.gross_level.iloc[-1]), rel_diff=float(b.gross_level.iloc[-1] / G.gross_level.iloc[-1] - 1))
# snapshot consistency: refreshed vs frozen close histories for all securities
def load_pair(root, s):
    o = json.loads((root / 'raw' / f"{s.replace('=', '_')}.json").read_text())['chart']['result'][0]; tz = o['meta'].get('exchangeTimezoneName', 'UTC')
    idx = pd.to_datetime(o['timestamp'], unit='s', utc=True).tz_convert(tz).tz_localize(None).normalize(); q = o['indicators']['quote'][0]
    return pd.DataFrame({'close': q['close'], 'adj': o['indicators']['adjclose'][0]['adjclose']}, index=idx)
mism, adjmoves = [], []
for s in list(SEC) + U['benchmarks']:
    a = load_pair(ROOTF, s); b = load_pair(ROOT, s); j = a.join(b, lsuffix='_f', rsuffix='_n', how='inner').dropna()
    if not np.allclose(j.close_f, j.close_n, rtol=1e-6): mism.append(s)
    ratio = j.adj_n / j.adj_f
    if ratio.max() - ratio.min() > 1e-5: adjmoves.append(s)
val['snapshot_consistency'] = dict(securities_checked=len(SEC) + len(U['benchmarks']), close_history_mismatches=mism, adj_history_rescaled_uniformly_only=len(adjmoves) == 0, names_with_nonuniform_adj_change=adjmoves)
(OUT / 'validation_log.json').write_text(json.dumps(val, ensure_ascii=False, indent=1, default=str), encoding='utf-8')
print(json.dumps({k: v for k, v in val.items()}, ensure_ascii=False, indent=1, default=str)[:3000])
print('purity now', purity_now, 'levels', fact['levels'])
