"""Build every point-in-time basket (dead coins count) from daily CMC snapshots, Sep 2022 to Sep 2026."""
import json, glob, os, datetime as dt, statistics as S
from baskets_def import CMC_BASKETS, EXCLUDE, MEME, AI, DEFI, GAMES
files=sorted(glob.glob('snapB/*.json')); days=[os.path.basename(f)[:10] for f in files]
snap={d:json.load(open(f)) for d,f in zip(days,files)}
px={d:{c[0]:c[6] for c in s if c[6]} for d,s in snap.items()}
has=lambda t,s:bool(set(t)&s)
P={"sol":"Solana","base":"Base","eth":"Ethereum","bnb":"BNB Smart Chain (BEP20)","ton":"TON","tron":"Tron20","sui":"Sui Network",
   "avax":"Avalanche C-Chain","arb":"Arbitrum","poly":"Polygon","rh":"Robinhood Chain"}
B={}
for b in CMC_BASKETS: B[b[0]]=(b[1],b[3])
for k,p in P.items():
    B.setdefault(k+"_memes",(p,lambda t:has(t,MEME)))
    B.setdefault(k+"_ai",(p,lambda t:has(t,AI)))
    B.setdefault(k+"_defi",(p,lambda t:has(t,DEFI) and not has(t,MEME) and not has(t,AI)))
B["majors"]=(None,lambda t:True)
def build(key,plat,rule,minvol=25000,topn=15):
    ex=EXCLUDE.get(key,set()); line=[]; lvl=1.0; mem=None; started=False; nm=[]
    for i in range(len(days)-1):
        d,n=days[i],days[i+1]
        if mem is None or dt.date.fromisoformat(d).weekday()==0:
            if key=="majors":
                xs=[c for c in snap[d] if c[3] is None and not c[9] and c[1] not in ("USDT","USDC") and c[6]>0]
                xs.sort(key=lambda c:-c[7]); m=[c[0] for c in xs[:10]]
            else:
                xs=[c for c in snap[d] if c[3]==plat and not c[9] and c[1] not in ex and rule(c[10]) and c[8]>=minvol and c[6]>0 and c[7]>0]
                xs.sort(key=lambda c:-c[7]); m=[c[0] for c in xs[:topn]]
            mem=m if len(m)>=4 else None
            if mem: nm.append(len(m))
        if mem is None:
            if started: line.append((n,lvl))
            continue
        rs=[]
        for cid in mem:
            a=px[d].get(cid); z=px[n].get(cid)
            if not a: continue
            if z is None:
                if any(cid in px[days[k]] for k in range(i+2,min(i+5,len(days)))): continue
                rs.append(-0.5); continue
            rs.append(max(-0.9,min(2.0,z/a-1)))
        if len(rs)<4:
            if started: line.append((n,lvl))
            continue
        started=True; lvl*=1+sum(rs)/len(rs); line.append((n,lvl))
    return line,(round(S.mean(nm),1) if nm else 0)
out={}
BTC=[(d,c[6]) for d in days for c in snap[d] if c[1]=="BTC" and c[3] is None]
out["btc"]={"plat":None,"line":BTC,"members":1}
for k,(p,r) in B.items():
    L,m=build(k,p,r)
    if len(L)>=150: out[k]={"plat":p,"line":L,"members":m}
    print(k,len(L),m)
json.dump(out,open('bk_all.json','w'))
