import pandas as pd, numpy as np
L = pd.read_csv("/mnt/user-data/uploads/an4/crew_v3_launch.csv"); u = pd.read_csv("run/uni.csv.gz")
print("launch rows", len(L), L.src.value_counts().to_dict(), "stop", L.stop.value_counts().to_dict(), "hops", L.hops.value_counts().sort_index().to_dict())
print("root != creator", round((L.root != L.creator).mean(), 3), "distinct roots", L.root.nunique(), "distinct creators", L.creator.nunique())
v = u[u.venue == "v3"].merge(L[["pool", "root", "creator", "stop", "hops"]].rename(columns={"creator": "cr"}), on="pool", how="left")
v["half"] = np.where(pd.to_datetime(v.first_trade) >= "2026-09-29", "B", "A")
print("v3 coins", len(v), "with root", v.root.notna().sum(), v.groupby("half").honest5x.agg(["count", "mean"]).round(3).to_dict())
A = v[v.half == "A"].groupby("root").agg(n=("pool", "size"), w=("honest5x", "sum")); A["r"] = A.w / A.n
baseA = v[v.half == "A"].honest5x.mean(); B = v[v.half == "B"]
for name, cond in (("v4 rule (>=5 coins, A >= 25%)", (A.n >= 5) & (A.r >= .25)), ("scaled (>=5 coins, A >= 2x base %.0f%%)" % (200 * baseA), (A.n >= 5) & (A.r >= 2 * baseA)),
                   ("any root with >=5 A coins", A.n >= 5)):
    good = set(A[cond].index); s = B[B.root.isin(good)]; rest = B[~B.root.isin(good) & B.root.notna()]
    print(name, "| roots", len(good), "| B coins", len(s), "B 5x", round(s.honest5x.mean(), 3) if len(s) else None, "| rest", len(rest), round(rest.honest5x.mean(), 3), "| lift", round(s.honest5x.mean() / rest.honest5x.mean(), 2) if len(s) else None)
print(A.sort_values("n", ascending=False).head(12).to_string())
# same root concentration in B
print(B.groupby("root").agg(n=("pool", "size"), w=("honest5x", "sum")).sort_values("n", ascending=False).head(8).to_string())
# repeat roots: does a root's A record predict B at all (per root correlation)
Bg = B.groupby("root").agg(nb=("pool", "size"), wb=("honest5x", "sum")); j = A.join(Bg, how="inner"); j = j[(j.n >= 3) & (j.nb >= 3)]
print("roots with >=3 coins in both halves", len(j), "corr A rate vs B rate", round(j.r.corr(j.wb / j.nb), 3) if len(j) > 2 else None)
v.to_csv("an44_v3coins.csv", index=False)
