
# 将油猴脚本获取的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
baseclass.makedirpath(baseclass.dalao_tran_dexscreen_path)
baseclass.makedirpath(baseclass.dalao_merge_path)
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")


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


def fun(gdf, tokenadd):
    # gdf = pd.DataFrame()
    arr_type = gdf['TYPE'].drop_duplicates().tolist()
    if ('Buy' not in arr_type or 'Sell' not in arr_type):
        return None
        # return pd.Series([])
    buy_mask = gdf['TYPE'] == 'Buy'
    sell_mask = gdf['TYPE'] == 'Sell'

    arr_buymoney = gdf[buy_mask]['SOL'].tolist()
    arr_sellmoney = gdf[sell_mask]['SOL'].tolist()
    arr_buytoken = gdf[buy_mask]['Token'].tolist()
    arr_selltoken = gdf[sell_mask]['Token'].tolist()
    Selltoken_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_selltoken])
    Buytoken_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_buytoken])
    Sellmoney_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_sellmoney])
    Buymoney_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_buymoney])
    Earn_dec = Sellmoney_dec - Buymoney_dec
    Earnper_dec = Earn_dec / \
        Buymoney_dec if Buymoney_dec != 0 else decimal.Decimal(
            -10)
    Amountper_dec = Selltoken_dec / Buytoken_dec if Buytoken_dec != 0 else decimal.Decimal(
        10)

    Buymoney = '{0:.2f}'.format(Buymoney_dec)
    Sellmoney = '{0:.2f}'.format(Sellmoney_dec)
    Earn = '{0:.2f}'.format(Earn_dec)
    Earnper = '{0:.2f}'.format(Earnper_dec)
    Buyamount = '{0:.2f}'.format(Buytoken_dec)
    Sellamount = '{0:.2f}'.format(Selltoken_dec)
    Amountper = '{0:.2f}'.format(Amountper_dec)
    Buycount = len(gdf[buy_mask]['TXN'].drop_duplicates())
    Sellcount = len(gdf[sell_mask]['TXN'].drop_duplicates())
    Maker = gdf['MAKER'].tolist()[0]
    FirstSwaptime = gdf['DATE'].min()
    return pd.DataFrame([[Maker,
                        FirstSwaptime,
                          Buymoney,
                          Sellmoney,
                          Earn,
                          Earnper,
                          Buycount,
                          Sellcount,
                          Buyamount,
                          Sellamount,
                          Amountper,
                          tokenadd]])


def filter_simple_dalao():

    csv_file_list = [f for f in os.listdir(
        baseclass.dalao_ori_tran_dexscreen_path) if f.endswith(".csv")]
    res_df = None
    big_amount_df = None

    for csv_file in csv_file_list:

        df = pd.read_csv(
            baseclass.dalao_ori_tran_dexscreen_path / csv_file, dtype=object)
        tokenadd = csv_file.split('_')[0]
        print(f"enter {tokenadd}")

        df = df[['DATE',
                 'TYPE',
                'SOL',
                 'Token',
                 'MAKER',
                 'TXN',
                 ]]

        df = df[df['TYPE'].isin(['Buy', 'Sell'])].reset_index(drop=True)
        df["DATE"] = pd.to_datetime(df["DATE"], format='%m-%d %H:%M:%S')
        min_date = df['DATE'].min()
        daxin_max_date = min_date + pd.Timedelta(seconds=2)
        daxin_mask = (df['DATE'] >= min_date) & (df['DATE'] <= daxin_max_date)
        arr_daxin_dalaoadd = df[daxin_mask]['MAKER'].drop_duplicates().tolist()
        drop_daxin_dalao_mask = (~ df['MAKER'].isin(arr_daxin_dalaoadd))
        df = df[drop_daxin_dalao_mask].reset_index(drop=True)

        df = df.groupby(by=['MAKER']).apply(
            lambda gdf: fun(gdf, tokenadd)).reset_index(drop=True)

        if (len(df) == 0):
            print("no transaction")
            return
        df.columns = ['Maker',
                      "FirstSwaptime",
                      'Buymoney',
                      'Sellmoney',
                      'Earn',
                      'Earnper',
                      'Buycount',
                      'Sellcount',
                      'Buyamount',
                      'Sellamount',
                      'Amountper',
                      'TokenAddress']

        # Rank,Maker,Buymoney,Sellmoney,Earn,Earnper,Buycount,Sellcount,Buyamount,Sellamount,Amountper,TokenAddress

        df['FirstSwaptime'] = df['FirstSwaptime'].dt.strftime('%m-%d %H:%M:%S')

        df["Amountper"] = df["Amountper"].astype(float)
        df["Buymoney"] = df["Buymoney"].astype(float)
        df["Sellmoney"] = df["Sellmoney"].astype(float)
        df["Earn"] = df["Earn"].astype(float)
        df["Earnper"] = df["Earnper"].astype(float)
        df["Buycount"] = df["Buycount"].astype(int)
        df["Sellcount"] = df["Sellcount"].astype(int)
        df["Earnper"] = df['Earnper'].round(2)
        df["Amountper"] = df['Amountper'].round(2)
        df.insert(12, 'isNormal', -1)
        df.to_excel(baseclass.dalao_tran_dexscreen_path / f"{tokenadd}.xlsx",
                    index=False)

        res_df = pd.concat([res_df, df], ignore_index=True)



    nor_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["Earnper"] >= 0.8)
        & (res_df["Buymoney"] >= 0.1)
        # & ~((res_df["Buycount"] >= 2) )
    )
    # nor_filter_mask = nor_filter_mask & False
    big1_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["Earnper"] >= 1)
        & (res_df["Buymoney"] >= 0.8)
        # & ~((res_df["Buycount"] >= 2) )
    )
    big2_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["Earnper"] >= 0.7)
        & (res_df["Buymoney"] >= 1.5)
        # & ~((res_df["Buycount"] >= 3) )
    )
    # big2_filter_mask = big2_filter_mask & False
  
    big3_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["Earnper"] >= 0.5)
        & (res_df["Buymoney"] >= 2)
        # & ~((res_df["Buycount"] >= 3) )
    )
    # big3_filter_mask = big3_filter_mask & False
 

    multiple_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["Earnper"] >= 2)
        & (res_df["Buymoney"] >= 0.05)
        # & ~((res_df["Buycount"] >= 2) )
    )
    multiple_df = res_df[multiple_filter_mask].reset_index(drop=True)
    
    print(f"len multiple_df ={len(multiple_df)}")


    filter_mask = (
        multiple_filter_mask
        | nor_filter_mask
        # | big1_filter_mask 
        # |  big2_filter_mask
        #  | big3_filter_mask 
      
                 
                   )
    # add_filter_mask = ((res_df["Buymoney"] <= 400))
    
   
    res_df = res_df[filter_mask].reset_index(drop=True)
    res_df = res_df.sort_values(by=["TokenAddress","FirstSwaptime"], ascending=[True,True])
    multiple_df = multiple_df.sort_values(by=["TokenAddress","FirstSwaptime"], ascending=[True,True])
    print(f"len df ={len(res_df)}")

    # 示例 获取结果如下https://dexscreener.com/solana/9s9sgqskfyzbygm45qblje4rt6calfa2dbhjrevlszrc?maker=47TwqZwwMGHc9CkJJxvVgFNGLDqBuSPy95KwUSTcLSti

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

    res_df.to_excel(baseclass.dalao_merge_path /
                    "un_onhand_dalao.xlsx", index=False)
    multiple_df.to_excel(baseclass.dalao_merge_path /
                    "multiple_df.xlsx", index=False)
    return


filter_simple_dalao()

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