
# 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
 
baseclass.makedirpath(baseclass.dalao_merge_path)
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

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


def get_fir_swap_info(gdf):
    # 未来使用
    arr_firswap_type = gdf["TYPE"].tolist()
    arr_firswap_token_amount = gdf["Token"].tolist()
    arr_firswap_eth_amount = gdf["SOL"].tolist()
    arr_firswap_token_amount = [decimal.Decimal( token_amount) for token_amount in arr_firswap_token_amount  ]
    arr_firswap_eth_amount = [decimal.Decimal( token_amount) for token_amount in arr_firswap_eth_amount  ]
    while len(arr_firswap_eth_amount) > 0:
        if arr_firswap_type[0]=="Buy":
            break
        else:
            arr_firswap_eth_amount.pop(0)
            arr_firswap_token_amount.pop(0)
            arr_firswap_type.pop(0)
    if len(arr_firswap_eth_amount) == 0:
        return "0","-10"
    
    fir_swap_tokenamount = arr_firswap_token_amount[0]
    fir_swap_costmain = arr_firswap_eth_amount[0]
    fir_swap_earntmain = -fir_swap_costmain
    while len(arr_firswap_eth_amount) > 0:
        # 去除 type为buy的交易 
        if arr_firswap_type[0]=="Buy":
            arr_firswap_eth_amount.pop(0)
            arr_firswap_token_amount.pop(0)
            arr_firswap_type.pop(0)
            continue
        # 现在  全是sell token earn eth
        cur_swap_tokenamount = arr_firswap_token_amount[0]
        cur_swap_eth = arr_firswap_eth_amount[0]
        arr_firswap_eth_amount.pop(0)
        arr_firswap_token_amount.pop(0)
        arr_firswap_type.pop(0)
        if fir_swap_tokenamount>=cur_swap_tokenamount:
            fir_swap_earntmain+=cur_swap_eth
            fir_swap_tokenamount-=cur_swap_tokenamount
        else:
            fir_swap_earntmain = fir_swap_earntmain+  fir_swap_tokenamount/cur_swap_tokenamount * cur_swap_eth
            fir_swap_tokenamount=decimal.Decimal(0)
        if fir_swap_tokenamount==0:
            break
     
    fir_cost_main =('{0:.2f}'.format(fir_swap_costmain) ) 
    fir_earn_percent=  ('{0:.2f}'.format(fir_swap_earntmain / fir_swap_costmain) )    if fir_swap_costmain != 0 else "-10"

    return fir_cost_main , fir_earn_percent
def fun(gdf, tokenadd):
      
    gdf=gdf[gdf['TYPE'].isin(["Buy", "Sell"])].reset_index(drop=True)
    if len(gdf)==0:
        return  None
    
    Maker = gdf['MAKER'].tolist()[0]
    FirstSwaptime = gdf['DATE'].min()
    arr_type = gdf['TYPE'].drop_duplicates().tolist()
    # if ('Buy' not in arr_type or 'Sell' not in arr_type):
    #     return None
    Maker_isNormal =" 1"
    if arr_type[0] =="Sell":
        Maker_isNormal = "0"
  
    Maker_isrelation = gdf['Maker_isrelation'].tolist()[0]
 
 
    fir_cost_main , fir_earn_percent = get_fir_swap_info(gdf=gdf)
    if float(fir_cost_main) ==0 :
        Maker_isNormal ="0"
 
    buy_mask = gdf['TYPE'].isin(["Buy"]) 
    sell_mask = gdf['TYPE'].isin(["Sell"])   
    arr_buymoney = gdf[buy_mask]['SOL'].tolist()
    arr_sellmoney = gdf[sell_mask]['SOL'].tolist()
    arr_buytokenamount = gdf[buy_mask]['Token'].tolist()
    arr_selltokenamount = gdf[sell_mask]['Token'].tolist()
    Selltokenamount_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_selltokenamount])
    Buytokenamount_dec = sum(
        [decimal.Decimal(token_dec) for token_dec in arr_buytokenamount])
    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 = Selltokenamount_dec / Buytokenamount_dec if Buytokenamount_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(Buytokenamount_dec)
    Sellamount = '{0:.2f}'.format(Selltokenamount_dec)
    Amountper = '{0:.2f}'.format(Amountper_dec)
    
    Buycount = len(gdf[buy_mask]['TXN'].drop_duplicates())
    Sellcount = len(gdf[sell_mask]['TXN'].drop_duplicates())

    return pd.DataFrame([[Maker,
                          Maker_isNormal,
                          Maker_isrelation,
                        FirstSwaptime,
                          Buymoney,
                          Sellmoney,
                          Earn,
                          Earnper,
                          Buycount,
                          Sellcount,
                          Buyamount,
                          Sellamount,
                          Amountper,
                          tokenadd,
                          fir_cost_main,
                          fir_earn_percent
                          ]])


def filter_simple_dalao():

    res_df = None
    big_amount_df = None
    global arr_token_address

    for tokenadd in arr_token_address:
   
 
        df = pd.read_excel( baseclass.dalao_merge_path/ f"rep_relationship_total_dalao_txn_{tokenadd}.xlsx",dtype=object)
        df["DATE"] = pd.to_datetime(df["DATE"])
    
        df=df.sort_values(by=["DATE"],ascending=[True])
        df = df[df['TYPE'].isin(['Buy', 'Sell'])].reset_index(drop=True)

        print(f"enter {tokenadd}")

        df["Maker_isNormal"] = "1"

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

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

        # Rank,Maker,Buymoney,Sellmoney,Earn,Earnper,Buycount,Sellcount,Buyamount,Sellamount,Amountper,TokenAddress
        #  isrelation
        df['FirstSwaptime'] = df['FirstSwaptime'].dt.strftime('%Y-%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["FirBuymoney"] = df["FirBuymoney"].astype(float)
        df["FirEarnper"] = df["FirEarnper"].astype(float)
        df.insert(12, 'isNormal', -1)
        df.insert(1, 'DexScreenURL', -1)

        df["DexScreenURL"] = df.apply(lambda ser: makescreenurl(
            "https://dexscreener.com/solana/" , f"{tokenadd }?maker={ser['Maker']}" ), axis=1)
     
        df.to_excel(baseclass.dalao_merge_path/f"relation_overview_{tokenadd}.xlsx",index=False)
        
        res_df = pd.concat([res_df, df], ignore_index=True)


    res_df.to_excel(baseclass.dalao_merge_path /
                    "ori_relation_dalao_merge.xlsx", index=False)
    
    
    nor_filter_mask = (
        (res_df["Amountper"] <= 1.01)
        & (res_df["FirEarnper"] >= 1)
        & (res_df["FirBuymoney"] >= 0.3)
        & ((res_df["Buycount"] <= 4) )
    )
    fir_big1_filter_mask = (
        (res_df["Amountper"] <= 1.1)
        & (res_df["FirEarnper"] >= 0.4)
        & (res_df["FirBuymoney"] >= 0.5)
        # & ((res_df["Buycount"] <= 4) )
    )
    big1_filter_mask = (
        (res_df["Amountper"] <= 1.1)
        & (res_df["Earnper"] >= 0.4)
        & (res_df["Buymoney"] >= 0.5)
        # & ((res_df["Buycount"] <= 4) )
    )
 

    filter_mask = (
        big1_filter_mask
        | fir_big1_filter_mask
        # nor_filter_mask
        # | big1_filter_mask
                     
                   )  
    
   
    res_df = res_df[filter_mask].reset_index(drop=True)
    res_df = res_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)

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

file_list = [f for f in os.listdir(
    baseclass.dalao_merge_path) if f.startswith("rep_relationship_total_dalao_txn_") ]
arr_token_address = [file.split("_")[-1].replace(".xlsx","") for file in file_list  ]
arr_token_address=list(set(arr_token_address))

print("arr_token_address= ",arr_token_address)
 
filter_simple_dalao()

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