
#  # 将不同时间的holders 合并为一个excel 并且一个时间一个sheet  \
# 目的在于提供一个excel表的框架， 之后所欲sheet的内容要被 special add 的hold info替换掉
import pandas as pd
import sys
import os
import datetime
import pytz

arr_file = []
merged_df = None
domains_df = None
token_add = ""
arr_date_range =[]
arr_df = []
token_add = '5puhwnyz2Tv8jSmmBD5DSqCwFVXwwPGZacymM7DQpump'
def get_nowdate():

    timestamp = datetime.datetime.now().timestamp()
    # print(timestamp)
    dt = datetime.datetime.fromtimestamp(timestamp)
    tz = pytz.timezone('Asia/Shanghai')
    normal_time_str = dt.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S')
    time_str = dt.astimezone(tz).strftime('%m%d%H%M')
    return time_str



def merge_df_fun():
    global arr_date_range ,arr_df
    
    arr_col_pct=[]
    
    global arr_file , merged_df , domains_df,token_add
    for index, file in enumerate(arr_file):
        date_range = file.replace(".csv","").split("_")
        date_range = date_range[-2]+"_"+date_range[-1]

        cur_df =   pd.read_csv(file ,dtype=object)
        cur_df=cur_df.dropna(subset=['holder_owner'])

        cur_domains_df = cur_df[['holder_owner' , 'domains_owned']]
        domains_df = pd.concat([domains_df, cur_domains_df  ]).dropna().drop_duplicates(subset=['holder_owner'])
         
        cur_df=cur_df[['holder_owner','amount_M']]
        cur_df =cur_df.astype({
            "amount_M":float,
        })
        cur_df = cur_df.round(2)
        cur_df.rename(columns={'amount_M': f'AM_{date_range}'}, inplace=True)
        arr_date_range.append(f'{date_range}')
        arr_col_pct.append(f'AM_{date_range}')
        if index==0 :
            merged_df = cur_df
            continue
        merged_df = pd.merge(merged_df, cur_df, on='holder_owner', how='outer')
  
    
   
    merged_df = pd.merge(merged_df, domains_df, on='holder_owner', how='left')

    merged_df["gmgn"] = merged_df.apply(lambda ser: makeurl(
    f"https://gmgn.ai/sol/token/{token_add}?tab=activity&maker={ser['holder_owner']}" , "gmgn" ), axis=1)

    merged_df["defined"] = merged_df.apply(lambda ser: makeurl(
     f"https://www.defined.fi/sol/{token_add}?maker={ser['holder_owner']}" , "defined" ), axis=1)
    
    
    arr_df.append(merged_df)
    
    for col_pct in arr_col_pct:
        cur_df=merged_df.sort_values(by=[col_pct],ascending = False)
        cur_df =cur_df.head(55)
        arr_df.append(cur_df)

  
def save_to_excel(out_excel):
    global arr_date_range ,arr_df
    with pd.ExcelWriter(out_excel) as writer:
        for idx ,cur_df in enumerate(arr_df):
            if idx==0:
                cur_df.to_excel(writer, sheet_name='Sheet1', index=False)
            else:
                cur_df.to_excel(writer, sheet_name=f'{arr_date_range[idx-1]}', index=False)  
    return


def makeurl( url,url_show):
    return '=HYPERLINK("{}","{}")'.format(url,  url_show)

if __name__ == "__main__":
 
    # if len(sys.argv)<2:
    #     print("args queshao ")
    #     sys.exit(1)
    
    arr_file = os.listdir(os.getcwd())

    arr_file = [file for file in arr_file if file.startswith( "dune_holders_xx")   and file.endswith(".csv")]

 
    arr_file.sort()
    print("read file: ",arr_file)
    merge_df_fun()
    time_str = get_nowdate()
    out_excel =f'003_merge_holders_excel_kuangjia_{time_str}.xlsx'
    save_to_excel(out_excel)
 
    