import sys, json, collections; sys.path.insert(0, "/root/fwa1")
from common import A, BC
C = json.load(open("/root/fwa1/coins2.json"))
TD = ["2026-09-30", "2026-10-01", "2026-10-02", "2026-10-03", "2026-10-04"]
ALLD = sorted(set(x["day"] for x in C))
def medpull(crew, eb):
    r = sorted(y["pull_s"] for y in C if y["crew"] == crew and y["rb"] < eb and y["pull_s"] is not None)
    return r[len(r) // 2] if len(r) >= 5 else None
def gx(x):
    m = medpull(x["tag"] or x["crew"], x["eb"])
    return "half3_10" if m is None else ("all2x" if m < 90 else "half3_10" if m < 200 else "all10x")
PASS = ["0x7028bab73f82dff14b199593abb76c8b6acb3aa9", "0x2dacdf0f44d07234832799a10a7cc5c8eff0223a", "0xdc5115eb561d3fe0c1e2363303635e890c757a21", "0x0ebe0078520ba12046a316d4ab92d275a14113e2", "0xb3f457a84de07051853d6a5a878d078df7156929"]
for cr in PASS:
    T = [x for x in C if x["crew"] == cr]
    import sqlite3, time
    lc = sqlite3.connect("file:/opt/pricepredict-data/crew.db?mode=ro", uri=True).execute("select count(*), max(t) from launch where root=? and fee=100", (cr,)).fetchone()
    print("CREWDB", cr, "pond launches", lc[0], "last", time.strftime("%d %b %H:%M", time.gmtime((lc[1] or 0) + 7*3600)))
    if not T: continue
    byd = collections.Counter(x["day"] for x in T)
    rec = sum(1 for x in T if x["tag"] == cr)
    print("CREW", cr, "coins", len(T), "days", dict(sorted(byd.items())), "tag recall %d/%d" % (rec, len(T)))
    row = []
    for d in sorted(byd):
        v = [x["ret"][gx(x)] for x in T if x["day"] == d]
        row.append("%s %+.0f%% (%d)" % (d[5:], 100 * sum(v) / len(v), len(v)))
    allv = sorted(x["ret"][gx(x)] for x in T)
    print("   general rule by day:", "; ".join(row))
    print("   total %+.0f%% n%d, best removed %+.0f%%" % (100 * sum(allv) / len(allv), len(allv), 100 * sum(allv[:-1]) / max(1, len(allv) - 1)))
# task 2: A and B/C at $4, all at 2x, gas $0.03 a side
F20 = 0.0101 + 0.0015; F4 = 0.0101 + 0.03 / 4
def at(ret, f_new):
    g = (1 + ret) / (1 - F20) ** 2
    return g * (1 - f_new) ** 2 - 1
print("TASK2 A/BC tag, all at 2x")
for size in (3, 4, 5):
    f = 0.0101 + 0.03 / size
    tot = 0; rows = []
    for d in TD:
        v = [at(x["ret"]["all2x"], f) for x in C if x["day"] == d and x["tag"] in (A, BC)]
        usd = size * sum(v); tot += usd; rows.append("%s $%.0f (%d coins)" % (d[5:], usd, len(v)))
    print("  $%d a coin: %s | avg $%.0f/day" % (size, "; ".join(rows), tot / len(TD)))
# same if X% of buys trigger a pull within 15 s (worst case from history)
