"""Honest early (2026) baselines for the Cycle 26 maximum, with leave-one-cycle-out errors.
1) climatology of cycles 1-25 and 10-25; 2) declining-phase precursor: 13-mo smoothed SN k years after cycle n's max vs R_{n+1}
(cycles 10-24); 3) polar field after max: see early_polar.py. Output: early_baselines.csv"""
import csv, os, numpy as np
HERE = os.path.dirname(os.path.abspath(__file__)); D = os.path.join(HERE, '..', 'data')
C = {int(r['cycle']): r for r in csv.DictReader(open(os.path.join(D, 'cycles.csv')))}
amp = {n: float(C[n]['max_sn']) for n in C}; tmax = {n: float(C[n]['max_decyear']) for n in C}
sm = {}
for l in open(os.path.join(D, 'SN_ms_tot_V2.0.txt')):
    p = l.split()
    if float(p[3]) >= 0: sm[float(p[2])] = float(p[3])
T = np.array(sorted(sm)); V = np.array([sm[t] for t in T])
def at(t):
    i = np.argmin(abs(T - t)); return V[i] if abs(T[i] - t) < 0.1 else np.nan
rows = []
for lo in (1, 10):
    a = np.array([amp[n] for n in range(lo, 26)])
    rows.append(dict(method=f'climatology, cycles {lo}-25', issue='any time', point=round(a.mean(), 1), sd=round(a.std(ddof=1), 1),
                     lo68=round(np.quantile(a, .16), 1), hi68=round(np.quantile(a, .84), 1), loo_rmse='', note=f'n={len(a)}'))
for k in (1.0, 1.5, 2.0, 3.0, 4.0):
    X = np.array([at(tmax[n] + k) for n in range(10, 25)]); Y = np.array([amp[n + 1] for n in range(10, 25)])
    res = []
    for i in range(len(X)):
        m = np.arange(len(X)) != i; b, a0 = np.polyfit(X[m], Y[m], 1); res.append(Y[i] - (a0 + b * X[i]))
    b, a0 = np.polyfit(X, Y, 1); x26 = at(tmax[25] + k); rm = np.sqrt(np.mean(np.square(res)))
    t_issue = tmax[25] + k + 0.5   # 13-month smoothing needs 6 more months
    rows.append(dict(method=f'declining phase: smoothed SN {k} yr after max, cycles 10-24', issue=f'{t_issue:.1f}',
                     point=round(a0 + b * x26, 1) if not np.isnan(x26) else 'not yet', sd='', lo68='', hi68='',
                     loo_rmse=round(rm, 1), note=f'r={np.corrcoef(X, Y)[0, 1]:.2f}; x25={x26}'))
with open(os.path.join(HERE, 'early_baselines.csv'), 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
for r in rows: print(r)
