import sys, datetime; sys.path.insert(0, "/root/fwa1")
from common import *
L, Wt = load_crew()
cre = collections.defaultdict(list)
for pool, b, tx, creator, root, fam, fee, t in L:
    if creator and b: cre[creator.lower()].append((b, root, t))

def tag(creator, b, hops, tcut=None):
    """walk funders; tcut = only use wallet rows written by crew.db before tcut (live check)"""
    w = creator.lower()
    for h in range(hops):
        r = Wt.get(w)
        if not r or not r[1]: return None, h
        if tcut is not None and (r[7] is None or r[7] > tcut): return "LATE", h
        f = r[1]
        prev = [x for x in cre.get(f, []) if x[0] < b and x[1]]
        if prev: return max(prev)[1], h + 1
        w = f
    return None, hops

def btime(b): return 1790787651 + (b-76678020)*0.101284
def bkday(t): return (datetime.datetime.utcfromtimestamp(t) + datetime.timedelta(hours=7)).strftime("%Y-%m-%d")
rows = [(p, b, c, r, t) for p, b, tx, c, r, fam, fee, t in L if fee == 100 and t and b and c and btime(b) >= 1790614800]
res = collections.defaultdict(collections.Counter)
hopn = collections.Counter()
for p, b, c, root, t in rows:
    bt = btime(b); d = bkday(bt); live = (t - bt) < 120
    if d < "2026-09-30": continue
    ab = root in (A, BC)
    for H in (2, 3, 5):
        tg, h = tag(c, b, H)
        if ab:
            res[(d, H)]["ab"] += 1; res[(d, H)]["hit"] += (tg == root)
        if tg in (A, BC) and tg != root: res[(d, H)]["falseAB"] += 1
        if tg and tg != root: res[(d, H)]["wrong_any"] += 1
        if tg: res[(d, H)]["tagged"] += 1
        if H == 5 and ab and tg == root: hopn[h] += 1
    if ab and live:
        for lag in (5, 10, 35):
            tg, h = tag(c, b, 5, tcut=bt + lag)
            res[(d, "live%d" % lag)]["ab"] += 1; res[(d, "live%d" % lag)]["hit"] += (tg == root)
        r = Wt.get(c.lower())
        res[(d, "rowlag")]["n"] += 1
        if r and r[7]: res[(d, "rowlag")]["lag_le10"] += (r[7] <= bt + 10)
        if r and r[3]: res[(d, "fund_before_s")]["sum"] += (b - r[3]) / 10
for k in sorted(res, key=str): print(k, dict(res[k]))
print("hops needed", hopn)
# creator funding lead time distribution (A/BC)
lead = sorted((b - Wt[c.lower()][3]) / 10 for p, b, c, root, t in rows if root in (A, BC) and Wt.get(c.lower()) and Wt[c.lower()][3])
print("creator funded s before launch: p10 %.0f p50 %.0f p90 %.0f n %d" % (lead[len(lead)//10], lead[len(lead)//2], lead[9*len(lead)//10], len(lead)))
