"""What if SWPC had adjusted its M/X probabilities for the GOES-16 scale change on 2019-12-09?
f = (number of post-switch flares >= threshold on the operational scale) / (number >= threshold on the legacy scale),
a pure measurement-scale factor from the flare size distribution. Poisson adjustment: p' = 1 - (1 - p)^f.
Scores raw vs adjusted lead-1..3 forecasts after the switch. Writes results/rescale_fix.csv."""
import numpy as np, pandas as pd
import os; R = os.environ.get('FLARE_ROOT', '/work/flare-forecasts')
e = pd.read_csv(f'{R}/data/xra_events.csv', parse_dates=['date']); post = e[e.date >= '2019-12-09']
a = pd.read_csv(f'{R}/data/flare_pairs.csv', parse_dates=['issue'])
rows = []
for ev, thr in (('M', 1e-5), ('X', 1e-4)):
    f = (post.flux >= thr).sum() / (post.flux_old >= thr).sum()
    for per, lo, hi in (('2019-12-09..2024', '2019-12-09', '2025-01-01'), ('2025..2026-10', '2025-01-01', '2027-01-01')):
        for lead in (1, 2, 3):
            d = a[(a.event == ev) & (a.lead == lead) & (a.issue >= lo) & (a.issue < hi)]
            padj = 1 - (1 - d.p) ** f
            bs, bsa = ((d.p - d.y) ** 2).mean(), ((padj - d.y) ** 2).mean()
            rows.append(dict(event=ev, f=f, period=per, lead=lead, n=len(d), oe_raw=d.y.sum() / d.p.sum(), oe_adj=d.y.sum() / padj.sum(), BS_raw=bs, BS_adj=bsa, BSS_adj_vs_raw=1 - bsa / bs))
r = pd.DataFrame(rows); r.to_csv(f'{R}/results/rescale_fix.csv', index=False); print(r.round(3).to_string(index=False))
