import json, datetime as dt, statistics as S, collections, math
import eng
CH = {'Solana': ['sol_pump','sol_bonk','sol_memes','sol_ai','sol_defi'], 'Base': ['base_memes','base_ai','base_defi'], 'Ton': ['ton_all']}
def ds(ts): return (dt.datetime.utcfromtimestamp(int(ts)).date()).isoformat()
ST = {}; DX = {}
for c in CH:
    ST[c] = {ds(x['date']): x['totalCirculatingUSD'].get('peggedUSD', 0) for x in json.load(open(f'st_{c}.json'))}
    DX[c] = {ds(a): b for a, b in json.load(open(f'dex_{c}.json'))['totalDataChart']}
def chg(m, d, n):
    d0 = (dt.date.fromisoformat(d) - dt.timedelta(n)).isoformat()
    return m[d] / m[d0] - 1 if d in m and d0 in m and m[d0] else None
def avg(m, d, n):
    xs = [m.get((dt.date.fromisoformat(d) - dt.timedelta(i)).isoformat()) for i in range(n)]
    xs = [x for x in xs if x]; return sum(xs) / len(xs) if len(xs) >= n * 0.8 else None
def feat(c, d):
    s7 = chg(ST[c], d, 7); s30 = chg(ST[c], d, 30)
    v7 = avg(DX[c], d, 7); v28 = avg(DX[c], d, 28)
    return dict(s7=s7, s30=s30, vol=(v7 / v28 - 1) if v7 and v28 else None)
rows = []
for c, ks in CH.items():
    for k in ks:
        dd, L = eng.SERIES[k]
        for i in range(len(L) - 14):
            f = feat(c, dd[i])
            if f['s7'] is None: continue
            rows.append(dict(c=c, k=k, d=dd[i], f14=L[i + 14] / L[i] - 1, **f))
print('rows', len(rows))
def bucket(name, key, cuts, lab):
    print('\n==', name)
    for per, lo, hi in (('2024-25', '2024-01-01', '2025-07-01'), ('2025-26', '2025-07-01', '2027')):
        for c in CH:
            xs = [r for r in rows if r['c'] == c and lo <= r['d'] < hi and r[key] is not None]
            if len(xs) < 50: continue
            out = []
            for j, (a, b) in enumerate(cuts):
                g = [r['f14'] for r in xs if a <= r[key] < b]
                out.append(f"{lab[j]}: n{len(g):4d} med{S.median(g)*100:+5.1f}% up{sum(1 for x in g if x>0)/max(1,len(g))*100:3.0f}%" if g else f"{lab[j]}: -")
            print(f"  {per} {c:6s} " + " | ".join(out))
bucket('stablecoin supply change 7d', 's7', [(-9, -0.01), (-0.01, 0.01), (0.01, 9)], ['OUT <-1%', 'FLAT', 'IN >+1%'])
bucket('stablecoin supply change 30d', 's30', [(-9, -0.03), (-0.03, 0.03), (0.03, 9)], ['OUT <-3%', 'FLAT', 'IN >+3%'])
bucket('DEX volume 7d vs 28d avg', 'vol', [(-9, -0.2), (-0.2, 0.2), (0.2, 9)], ['falling >20%', 'flat', 'rising >20%'])
json.dump(rows, open('flowrows.json', 'w'))
