import json, sys, collections, os
sys.path.insert(0, '/tmp/run'); import feat3
from feat import RT, SUP, KL, tier_of
def peak7(tok, t0):
    k = KL.get(tok); s = SUP.get(tok)
    if not k or not s or not t0: return None, None, None
    w = [x for x in k if t0 - 3600 <= x[0] <= t0 + 7 * 86400]
    if not w: return None, 'no_kline', None
    if w[0][0] > t0 + 6 * 3600: return None, 'kline_late', None
    cl = sorted((x[4] * s for x in w), reverse=True); pk = cl[1] if len(cl) > 1 else cl[0]
    ts = {th: next(((x[0] - t0) / 3600 for x in w if x[4] * s >= th), None) for th in (5e5, 1e6, 5e6)}
    allc = sorted((x[4] * s for x in k), reverse=True); pk_all = allc[1] if len(allc) > 1 else allc[0]
    return pk, ts, pk_all
src = {}
for fn in ('/tmp/run/raw_win.jsonl', '/tmp/run/raw.jsonl', '/tmp/run/raw_fix.jsonl', '/tmp/run/raw_ctl2.jsonl'):
    if not os.path.exists(fn): continue
    for l in open(fn):
        o = json.loads(l)
        if o.get('err') or o.get('fix_err') or o.get('tr') is None: continue
        src[o['tok']] = o        # later files (fixes) override
rows = []
for t, o in src.items():
    try: f = feat3.feats3(o)
    except Exception as e: print('err', t, repr(e)[:80]); continue
    if f.get('S') is None: continue
    f['fixed'] = int('fixed_from' in o)
    if o['kind'] == 'runner':
        pk, ts, pka = peak7(t, f['start_ts']); f['peak7'] = pk; f['pk_all'] = pka
        f['t_hit'] = ts if isinstance(ts, dict) else None; f['kl_note'] = ts if isinstance(ts, str) else None
        r = RT[t]; f['sym'] = r['symbol']; f['name'] = r['name']; f['lp'] = r['launchpad']; f['ath'] = r['ath_mc']
    else:
        f['sym'] = o.get('sym'); f['name'] = o.get('name')
    f['namek'] = feat3.name_kinds((f.get('name') or '') + ' ' + (f.get('sym') or ''))
    rows.append(f)
json.dump(rows, open('/tmp/run/feats3.json', 'w'))
c = collections.Counter()
for r in rows:
    if r['kind'].startswith('control'): c[r['kind']] += 1
    elif r.get('peak7') is None: c['runner_nopeak:' + str(r.get('kl_note'))] += 1
    else: c['tier %g' % tier_of(r['peak7'])] += 1
print(sorted(c.items()))
