
from base_class import *
from base_class import BaseVariableFunction


baseclass = BaseVariableFunction(__file__)
old_print = print


def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)


print = timestamped_print

print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
obj_dalao_2_profit_df = {

}

obj_dalao_2_arr_token = {

}


obj_token_2_arr_dalao = {

}
arr_total_str_tokenaddress = []

obj_dalao_2_buycounts = {

}


def makescreenurl(urlname, urlparam):
    urlname = urlname + urlparam
    return '=HYPERLINK("{}","{}")'.format(urlname, urlname)


df = pd.read_excel(baseclass.dalao_total_ana_fm_path /
                   "anaing_dalao.xlsx", dtype=object)


arr_str_dalaoaddress = df["add"].tolist()
for str_dalaoaddress in arr_str_dalaoaddress:
    if not (baseclass.dalao_ana_fm_path/str_dalaoaddress/f"onetxhash_onerow_profit_{str_dalaoaddress}.csv").exists():
        continue
    cur_df = pd.read_csv(baseclass.dalao_ana_fm_path / str_dalaoaddress /
                         f"onetxhash_onerow_profit_{str_dalaoaddress}.csv", dtype=object)
    cur_df = cur_df.astype({
        'timestamp': int,
        'buy_counts': int,
        'sell_counts': int,
        'swap_eth_amount': float,
        'outtoken_per': float,
        'cost_main': float,
        'earn_main': float,
        'earn_percent': float
    })
    cur_df = cur_df[cur_df["cost_main"] != 0].reset_index(drop=True)
    obj_dalao_2_profit_df[str_dalaoaddress] = cur_df

    obj_dalao_2_arr_token[str_dalaoaddress] = cur_df["swap_tokenaddress"].drop_duplicates(
    ).tolist()
    arr_total_str_tokenaddress.extend(cur_df["swap_tokenaddress"].tolist())


arr_total_str_tokenaddress = list(set(arr_total_str_tokenaddress))
print("arr_total_str_tokenaddress len=", len(arr_total_str_tokenaddress))

for str_tokenaddress in arr_total_str_tokenaddress:
    # print("enter ", str_tokenaddress)
    obj_token_2_arr_dalao[str_tokenaddress] = []
    for str_dalaoaddress in arr_str_dalaoaddress:
        if str_tokenaddress in obj_dalao_2_arr_token[str_dalaoaddress]:
            # dexurl = f"https://dexscreener.com/solana/{str_tokenaddress}?maker={str_dalaoaddress}"
            obj_token_2_arr_dalao[str_tokenaddress].append(
                str_dalaoaddress)

# 获取 dalao持有的所有token 以及 token->持有该token的所有dalao 的df
df = pd.DataFrame.from_dict(obj_token_2_arr_dalao, orient='index')


df = df.reset_index(names=['add'], drop=False)
df.insert(
    loc=1, column="DexScreenURL", value="")

df['DexScreenURL'] = df.apply(lambda ser: makescreenurl(
    "https://dexscreener.com/solana/", f"{ser['add']}"), axis=1)


df.to_excel(baseclass.dalao_total_ana_fm_path /
            "anaed_token_2_dalao.xlsx", index=False)

# 获得很多个dalao都持有的token->持有该token的多有dalao df
repeat_token_df = df[~(df[1].isna())].reset_index(drop=True)

repeat_token_df.to_excel(
    baseclass.dalao_total_ana_fm_path/"repeat_token_df.xlsx", index=False)

arr_str_dalaoaddress_repeat_token = arr_str_dalaoaddress
new_arr_str_dalaoaddress_repeat_token = arr_str_dalaoaddress_repeat_token


# 获取dalao列表中有两个共同购买的token new_arr_token

for idx_df in repeat_token_df.index:
    cur_row = repeat_token_df.loc[idx_df,]
    cur_str_tokenaddress = cur_row['add']
    # print(f"cur_str_tokenaddress= {cur_str_tokenaddress}")
    dexscreenurl = cur_row['DexScreenURL']
    arr_cur_row = cur_row.tolist()
    arr_cur_row.remove(cur_str_tokenaddress)
    arr_cur_row.remove(dexscreenurl)
    arr_cur_row = set(arr_cur_row)
    arr_cur_row.discard(None)
    arr_cur_row = list(arr_cur_row)
    if len(set(arr_cur_row) & set(new_arr_str_dalaoaddress_repeat_token)) >= 2:
        new_arr_str_dalaoaddress_repeat_token.append(cur_str_tokenaddress)

# 获取包含 new_arr_token 的df
new_repeat_token_df = repeat_token_df[repeat_token_df["add"].isin(
    new_arr_str_dalaoaddress_repeat_token)].reset_index(drop=True)


new_repeat_token_df = new_repeat_token_df.sort_values(
    by=['add'], ascending=[True]).reset_index(drop=True)

new_repeat_token_df.to_excel(
    baseclass.dalao_total_ana_fm_path/"new_repeat_token_df.xlsx", index=False)
print(f"new_repeat_token_df len= {len(new_repeat_token_df)}")

# 将拥dalao 关于此tokne的protfi汇总，保存为total_dalao_profit_df
total_dalao_profit_df = None
for idx_df in new_repeat_token_df.index:
    cur_row = new_repeat_token_df.loc[idx_df,]
    cur_str_tokenaddress = cur_row['add']
    dexscreenurl = cur_row['DexScreenURL']
    arr_cur_row = cur_row.tolist()
    arr_cur_row.remove(cur_str_tokenaddress)
    arr_cur_row.remove(dexscreenurl)
    arr_cur_row = set(arr_cur_row)
    arr_cur_row.discard(None)
    arr_cur_row = list(arr_cur_row)
    for str_dalaoaddress in arr_cur_row:
        # obj_str_dalaoaddress_repeat_token_2_buytokennum[str_dalaoaddress][0] += 1
        cur_dalao_df = obj_dalao_2_profit_df[str_dalaoaddress]
        cur_dalao_gdf = cur_dalao_df[cur_dalao_df["swap_tokenaddress"]
                                     == cur_str_tokenaddress].reset_index(drop=True)
        cur_dalao_gdf['dalaoaddress'] = str_dalaoaddress
        total_dalao_profit_df = pd.concat(
            [total_dalao_profit_df, cur_dalao_gdf])


def get_dalaofirsttimestamp(gdf):
    gdf["dalaofirsttimestamp"] = gdf["datetime"].min()
    return gdf


total_dalao_profit_df['datetime'] = pd.to_datetime(
    total_dalao_profit_df['timestamp'], unit='s')

total_dalao_profit_df["dalaofirsttimestamp"] = None
total_dalao_profit_df = total_dalao_profit_df.groupby(['swap_tokenaddress', 'dalaoaddress']).apply(
    lambda gdf: get_dalaofirsttimestamp(gdf)).reset_index(drop=True)


# total_dalao_profit_df.insert(
#     loc=2, column="DexScreenURL", value="")


total_dalao_profit_df['DexScreenURL'] = total_dalao_profit_df.apply(lambda ser: makescreenurl(
    "https://dexscreener.com/solana/", f"{ser['swap_tokenaddress']}?maker={ser['dalaoaddress']}"), axis=1)


total_dalao_profit_df = total_dalao_profit_df.sort_values(
    by=["dalaofirsttimestamp", "swap_tokenaddress", "dalaoaddress", "datetime"], ascending=[True, True, True, True]).reset_index(drop=True)


total_dalao_profit_df["idx_dalao"] = -1


def get_dalaobuyidx(gdf):

    cur_gdf = gdf[["dalaoaddress", "dalaofirsttimestamp"]].drop_duplicates(
    ).sort_values(by=["dalaofirsttimestamp"], ascending=[True])
    arr_str_dalaoaddress = cur_gdf["dalaoaddress"].tolist()
    obj_dalaoaddress_2_idx = {}
    for idx_str_dalaoaddress in range(0, len(arr_str_dalaoaddress)):
        str_dalaoaddress = arr_str_dalaoaddress[idx_str_dalaoaddress]
        obj_dalaoaddress_2_idx[str_dalaoaddress] = idx_str_dalaoaddress
    gdf["idx_dalao"] = gdf["dalaoaddress"].map(obj_dalaoaddress_2_idx)
    return gdf


total_dalao_profit_df = total_dalao_profit_df.groupby(['swap_tokenaddress']).apply(
    lambda gdf: get_dalaobuyidx(gdf)).reset_index(drop=True)


total_dalao_profit_df.to_excel(
    baseclass.dalao_total_ana_fm_path/"total_dalao_profit_df.xlsx", index=False)
# 计算 所有 outtokenper小于=1 的 dalaoaddress的盈利  并且计算总盈利 和 去重第一次购买的总盈利


print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
