"""Final return on POLYMARKET for the four tracked strategies:
   {baseline, momentum} x {flat, kelly}.

Reuses the canonical evaluate() from forward_test_drift_momentum.py UNCHANGED, so
sizing/metrics are identical to the Kalshi forward test. Only the signal source is
swapped: Polymarket MID (poly_*_price) instead of kalshi mid/ask.

CAVEAT: the poly backfill is MID-ONLY (no historical bid/ask). So a0==m0 and aL==mL
(execute at mid). This is the same optimistic mid-pricing behind the +17.4% figure;
real ask execution would be worse (Kalshi mid->ask cost ~2.5pts and dropped n).
"""
import csv, glob, os
from collections import defaultdict
import sys
sys.path.insert(0, r'E:\soccer')
from forward_test_drift_momentum import evaluate, BAND, COMBOS, _pts, _f, _result

BACKFILL_DIR = r'E:\soccer\poly_backfill'

def build_poly_signals():
    fixtures = defaultdict(list)
    for path in glob.glob(os.path.join(BACKFILL_DIR, '*_polybackfill.csv')):
        with open(path, newline='', encoding='utf-8') as fh:
            for r in csv.DictReader(fh):
                fixtures[(r.get('game_date'), r.get('league'),
                          r.get('home'), r.get('away'))].append(r)

    sigs = []
    for (gd, league, home, away), rows in fixtures.items():
        if not gd:
            continue
        pre = sorted([(_pts(r['timestamp']), r) for r in rows
                      if (r.get('status') or '').upper() == 'PRE' and _pts(r['timestamp'])],
                     key=lambda t: t[0])
        if len(pre) < 2:
            continue
        ftr = _result(rows)
        if ftr is None:
            continue
        cands = []
        for side in ('home', 'away'):
            pricek, pfk = f'poly_{side}_price', f'pin_fair_{side}'
            ent = None
            for ts, r in pre:
                m = _f(r.get(pricek)); pf = _f(r.get(pfk))
                if m is not None and pf is not None and 0 < m < 1 and pf > 0:
                    clv = (pf - m) / pf                       # poly CLV vs Pinnacle fair
                    if BAND[0] <= clv < BAND[1]:
                        ent = (ts, m, pf, clv); break
            if not ent:
                continue
            _, m0, p0, clv0 = ent                              # mid-only: ask == mid
            # last pre-KO snapshot with a poly price + pin_fair
            mL = pL = None
            for ts, r in reversed(pre):
                mv, pv = _f(r.get(pricek)), _f(r.get(pfk))
                if mv is not None and pv is not None and 0 < mv < 1 and pv > 0:
                    mL, pL = mv, pv; break
            if mL is None:
                continue
            won = (ftr[0] == 'H' and side == 'home') or (ftr[0] == 'A' and side == 'away')
            cands.append(dict(gd=gd, league=league, side=side, clv=clv0,
                              a0=m0, p0=p0, aL=mL, pL=pL, won=won, drift=mL - m0))
        if cands:
            sigs.append(max(cands, key=lambda d: d['clv']))    # higher-CLV side (dedupe)
    sigs.sort(key=lambda s: s['gd'])
    return sigs


if __name__ == '__main__':
    sigs = build_poly_signals()
    print(f"POLYMARKET signals over backfill window: {len(sigs)} fixtures "
          f"({sigs[0]['gd']} -> {sigs[-1]['gd']})\n")
    print(f"  {'strategy':16s} {'n':>4} {'WR':>6} {'total':>9} {'final $':>10} {'g/bet':>9} {'MDD':>8} {'ROIturn':>8}")
    for tag, sig, stk, nm in COMBOS:
        if sig == 'edge':
            continue   # only the 4 tracked strategies
        d = evaluate(sigs, sig, stk)
        print(f"  {nm:16s} {d['n']:4d} {d['wr']:5.1f}% {d['total']:+8.1f}% "
              f"{d['final']:>10,.0f} {d['g']:+8.4f}% {d['mdd']:+7.1f}% {d['roiturn']:+7.1f}%")
