"""Proof of Foresight: score one round against Rosstat's releases (protocol 1.0, see PROTOCOL.md).
  python foresight/score.py COMMITMENT_JSON OUT_JSON FIRST_RELEASE_XLSX... [--latest LATEST_XLSX]
A target period is scored only with the first file that contains it (primary resolution, the value as first published).
With --latest the same items are also scored against the latest file (secondary resolution) and every revision is logged.
Accuracy only: integrity is checked separately (verify.py) and is never mixed into these numbers."""
import hashlib, json, math, os, random, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

ALPHAS = [(0.05, 0.95), (0.25, 0.75)]   # central 90% and 50% intervals from the committed quantiles
B, SEED = 2000, 20261128

def wis(q, y):
    """weighted interval score on the log scale (Bracher et al. 2021) for quantiles q05,q25,q50,q75,q95"""
    ly = math.log(y); lq = [math.log(v) for v in q]
    s = 0.5 * abs(ly - lq[2])
    for (lo, hi), a in zip(((lq[0], lq[4]), (lq[1], lq[3])), (0.1, 0.5)):
        s += a / 2 * ((hi - lo) + 2 / a * max(0, lo - ly) + 2 / a * max(0, ly - hi))
    return s / (len(ALPHAS) + 0.5)

def item_scores(f, y):
    return {'ae_b0': abs(math.log(y / f['b0'])), 'ae_b1': abs(math.log(y / f['b1'])), 'ae_m1': abs(math.log(y / f['m1'][2])),
            'wis_m1': wis(f['m1'], y), 'in90': f['m1'][0] <= y <= f['m1'][4], 'in50': f['m1'][1] <= y <= f['m1'][3], 'exact_b0': abs(y - f['b0']) < 0.005}

def summarise(items, rng_seed=SEED):
    if not items: return None
    n = len(items); mean = lambda k, xs: sum(x[k] for x in xs) / len(xs)
    out = {'n': n, 'mae_b0': mean('ae_b0', items), 'mae_b1': mean('ae_b1', items), 'mae_m1': mean('ae_m1', items), 'wis_m1': mean('wis_m1', items),
           'coverage90': mean('in90', items), 'coverage50': mean('in50', items), 'exact_b0': mean('exact_b0', items)}
    out['skill_m1_vs_b0'] = 1 - out['mae_m1'] / out['mae_b0'] if out['mae_b0'] else None
    out['skill_b1_vs_b0'] = 1 - out['mae_b1'] / out['mae_b0'] if out['mae_b0'] else None
    out['relative_wis_m1_vs_b0'] = out['wis_m1'] / out['mae_b0'] if out['mae_b0'] else None   # WIS of a point forecast equals its absolute error
    # cluster bootstrap by region: items of one region (all series, both horizons) are resampled together
    by = {}
    for x in items: by.setdefault(x['u'], []).append(x)
    units = sorted(by); rng = random.Random(rng_seed); diffs, dw = [], []
    for _ in range(B):
        xs = [x for u in (rng.choice(units) for _ in units) for x in by[u]]
        diffs.append(mean('ae_m1', xs) - mean('ae_b0', xs)); dw.append(mean('wis_m1', xs) - mean('ae_b0', xs))
    diffs.sort(); dw.sort()
    d = [x['ae_m1'] - x['ae_b0'] for x in items]; md = sum(d) / n
    var_iid = sum((v - md) ** 2 for v in d) / (n - 1) / n if n > 1 else 0.0
    mb = sum(diffs) / B; var_boot = sum((v - mb) ** 2 for v in diffs) / (B - 1)
    out.update({'mae_diff_m1_b0': md, 'mae_diff_m1_b0_ci95': [diffs[int(0.025 * B)], diffs[int(0.975 * B) - 1]],
                'wis_m1_minus_ae_b0_ci95': [dw[int(0.025 * B)], dw[int(0.975 * B) - 1]], 'clusters': len(units),
                'design_effect': (var_boot / var_iid) if var_iid > 0 else None, 'effective_n': (n * var_iid / var_boot) if var_boot > 0 else None})
    return {k: (round(v, 6) if isinstance(v, float) else [round(a, 6) for a in v] if isinstance(v, list) else v) for k, v in out.items()}

def score(c, first, latest=None, files=None):
    """first: {period: {(region, series): value}} from the first file containing each period; latest likewise"""
    items, unresolved, revisions = [], [], []
    for f in c['forecasts']:
        if f['t'] not in first: continue
        y = first[f['t']].get((f['u'], f['s']))
        if not y: unresolved.append({'u': f['u'], 's': f['s'], 't': f['t'], 'h': f['h']}); continue
        it = dict(item_scores(f, y), u=f['u'], s=f['s'], t=f['t'], h=f['h'], y=y)
        if latest and f['t'] in latest:
            yl = latest[f['t']].get((f['u'], f['s']))
            if yl and abs(yl - y) >= 0.005: revisions.append({'u': f['u'], 's': f['s'], 't': f['t'], 'first': y, 'latest': yl})
            if yl: it['latest'] = dict(item_scores(f, yl))
        items.append(it)
    cls = {s: v['class'] for s, v in c['series'].items()}
    groups = {'all': items}
    for h in (1, 2): groups[f'h{h}'] = [x for x in items if x['h'] == h]
    for k in sorted(set(cls.values())): groups[f'class:{k}'] = [x for x in items if cls[x['s']] == k]
    for s in sorted(cls): groups[f'series:{s}'] = [x for x in items if x['s'] == s]
    res = {'type': 'wir.foresight.score/v1', 'round': c['round'], 'protocol': c['protocol']['version'],
           'commitment_sha256': hashlib.sha256(json.dumps(c, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()).hexdigest(),
           'resolved_targets': sorted(first), 'resolution_files': files or {}, 'primary': {k: summarise(v) for k, v in groups.items() if v},
           'unresolved': unresolved, 'revisions': revisions, 'items': [{k: (round(v, 6) if isinstance(v, float) else v) for k, v in x.items() if k != 'latest'} for x in items]}
    if latest:
        li = [dict(x['latest'], u=x['u'], s=x['s'], h=x['h']) for x in items if 'latest' in x]
        res['secondary'] = {'all': summarise(li)}
    return res

if __name__ == '__main__':
    from rosstat import parse
    args = sys.argv[1:]; latest_path = None
    if '--latest' in args: i = args.index('--latest'); latest_path = args[i + 1]; args = args[:i] + args[i + 2:]
    cpath, out, firsts = args[0], args[1], args[2:]
    c = json.load(open(cpath, encoding='utf-8'))
    targets = {t['period'] for t in c['targets']}; first, files = {}, {}
    for p in sorted(firsts):   # files named ..._MM-YYYY.xlsx; the earliest file containing a target is its first release
        b = open(p, 'rb').read(); H, periods = parse(b)
        for t in targets:
            if t in periods and t not in first:
                first[t] = {(r, s): v for (pp, r, s), v in H.items() if pp == t}; files[t] = {'file': os.path.basename(p), 'sha256': hashlib.sha256(b).hexdigest()}
    latest = None
    if latest_path:
        H, periods = parse(open(latest_path, 'rb').read()); latest = {t: {(r, s): v for (pp, r, s), v in H.items() if pp == t} for t in targets if t in periods}
    res = score(c, first, latest, files)
    json.dump(res, open(out, 'w', encoding='utf-8'), ensure_ascii=False, sort_keys=True, indent=1)
    print(json.dumps({k: res['primary'].get(k) for k in ('all', 'h1', 'h2')}, indent=1))
