


# https://dexscreener.com/?rankBy=volume&order=desc&chainIds=solana&maxAge=24&min24HTxns=500&min24HSells=200&min24HChg=100

# 将油猴脚本获取的top trader
from base_class import BaseVariableFunction
from base_class import *
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---------------")

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


buytoken_df_file_list = [f for f in os.listdir(
    baseclass.dalao_merge_path) if f.startswith("buytoken_df_") ]
arr_token_address = [tokenadd.split("_")[-1].replace(".xlsx","") for tokenadd in buytoken_df_file_list   ]
arr_token_address=list(set(arr_token_address))
print(arr_token_address)
df = None
for tokenadd in arr_token_address:
    cur_buytoken_df = pd.read_excel(baseclass.dalao_merge_path /
                    f"buytoken_df_{tokenadd}.xlsx", dtype=object)
    cur_buytoken_df["TokenAddress"] = tokenadd
    df = pd.concat([df,cur_buytoken_df])


old_token_df = pd.read_excel(baseclass.dalao_merge_path /"old_token.xlsx" , dtype=object)
arr_old_token =  old_token_df["token"].tolist()

arr_duplicates_dalao = df[df.duplicated(subset=["Maker"])]["Maker"].tolist()
df = df[df["Maker"].isin(arr_duplicates_dalao)]

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

df["freq"] = 1
freq = df['Maker'].value_counts()
 
df['freq'] = df['Maker'].map(freq)
df = df.astype({
    "MinBuyPrice":float,
    "Amountper":float,
    "Earnper":float,
    "Buycount":int,

})
# df = df[df["Buycount"]<=5]
# df = df[df["Amountper"]<=1]

df = df[ 
 ~(  ( df["Earnper"]<=0.4 )
    & (df["Amountper"]>=0.9) 
     & (df["Amountper"] <=1) 
     &(df["Buycount"]<=2)
    )
   
    ]



def filter_buycount(gdf):
    cur_freq = gdf["freq"].tolist()[0]
    if cur_freq == 2:
        if len(gdf["Maker"])==1:
            return None
    elif  cur_freq == 3:
        if len(gdf["Maker"])==1:
            return None
    # elif  cur_freq >=4:
    #     if len(gdf["Maker"]) / cur_freq <0.4:
    #         return None
    elif  cur_freq >=4:
        if len(gdf["Maker"])>=2:
            return None
        
    return gdf

def filter_oldtoken(gdf):
    cur_freq = gdf["freq"].tolist()[0]
    # 获取当前dalao 含有的old token 的数量
    cur_old_token_count = len(gdf[gdf["is_old_token"]==1])
    if  ( cur_old_token_count)==cur_freq:
        # 如果全是 old token  不要这个dalao  pass
        return None
        
    return gdf

df = df.groupby(by=["Maker"],group_keys=False).apply(lambda gdf : filter_buycount(gdf))
df["is_old_token"] = 0
df.loc[df["TokenAddress"].isin(arr_old_token) , "is_old_token"]  = 1

df = df.groupby(by=["Maker"],group_keys=False).apply(lambda gdf : filter_oldtoken(gdf))
df = df.reset_index(drop=True)
 
df=df.sort_values(by=["freq","Maker"],ascending=[False,True])
cur_datetime = int(time.time())
df.to_excel(baseclass.dalao_merge_path /f"{cur_datetime}_repeat_dalao.xlsx",index=False)


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