
# from datetime import datetime, timezone
# from playwright.async_api import async_playwright, Playwright
# from playwright.sync_api import expect
 
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)

baseclass.makedirpath(baseclass.ana_dalao_relation_by_solscan_path )

 
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---------------")
 
arr_exclude_address=[
    
]
arr_realtion_address =[]

now_time = time.time()
df = pd.read_excel(baseclass.dalao_tran_gmgnOrdex_path /
                "input_dalao.xlsx", dtype=object)
arr_str_dalaoaddress = df['dalaoaddress'].tolist()
# arr_str_dalaoaddress=arr_str_dalaoaddress[0:2]
arr_realtion_address  = arr_realtion_address + arr_str_dalaoaddress
str_tokenaddress_dalao_source = "4GULMPKBJLruChBZWksZzukAg1AjSCmCTMn9ny2Xpump"
find_depth = "depth_01"

baseclass.makedirpath(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source    )
baseclass.makedirpath(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source /find_depth )
baseclass.makedirpath(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source /find_depth/"mid" )
baseclass.makedirpath(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source /find_depth/"final" )


def drop_ex_txhash(gdf):
    is_ex = False
    if( ( gdf["action"] != "TRANSFER" )
        | (gdf["timestamp"]<now_time - 1*30* 24* 3600 )
        |( gdf["from"].isin(arr_exclude_address))
        |( gdf["to"].isin(arr_exclude_address))
        ).any( ):
        is_ex = True
    
    if is_ex:
        return None
    if (  set( gdf["from"].tolist() ).intersection(gdf["to"].tolist())   ):
        is_ex = True
    if is_ex:
        return None
    return gdf


def sum_same_tx_from_to(gdf ):
    gdf["amount"] = sum(gdf["amount"])
    gdf=gdf.drop_duplicates()
    return gdf

def sum_same_from_to(gdf ):
    gdf["timestamp"] = max(gdf["timestamp"] )
    gdf["datetime"] = max(gdf["datetime"] )
    gdf["amount"] = sum(gdf["amount"])
    gdf=gdf.drop_duplicates()
    return gdf
def main():
    global arr_exclude_address
    for str_dalaoaddress in arr_str_dalaoaddress:
        print(f"enter {str_dalaoaddress}")
        cur_arr_realtion_address =arr_realtion_address.copy()
        cur_arr_realtion_address.remove(str_dalaoaddress)
        

        df_sol_transfer =pd.read_csv(baseclass.dalao_solscan_info_path / f"sol_transfer_{str_dalaoaddress}.csv" ,dtype=object)
        df_sol_transfer = df_sol_transfer.astype({
            "Time":int,
        })
        
        # df_token_inflow =pd.read_csv(baseclass.dalao_solscan_info_path / f"token_inflow_{str_dalaoaddress}.csv" ,dtype=object)
        # df_token_outflow =pd.read_csv(baseclass.dalao_solscan_info_path / f"token_outflow_{str_dalaoaddress}.csv" ,dtype=object)
        df_token_transfer =pd.read_csv(baseclass.dalao_solscan_info_path / f"token_transfer_{str_dalaoaddress}.csv" ,dtype=object)
        df_token_transfer=df_token_transfer.astype({
            "Time":int,
        })
        
        time_min_df_token_transfer = df_token_transfer["Time"].min()
        df_sol_transfer= df_sol_transfer[df_sol_transfer["Time"]>time_min_df_token_transfer].reset_index(drop=True)
        
        df_usdc_transfer =pd.read_csv(baseclass.dalao_solscan_info_path / f"usdc_transfer_{str_dalaoaddress}.csv" ,dtype=object)
        

        # Signature,Time,Action,From,To,Amount,Decimals,TokenAddress
        
        # inflow out time 选最大的那一个
        

        arr_no_sol_transfer_tx_01 = df_token_transfer["Signature"].tolist() +  df_usdc_transfer["Signature"].tolist()
        
        df_sol_transfer = df_sol_transfer[~df_sol_transfer["Signature"].isin(arr_no_sol_transfer_tx_01)].reset_index(drop=True)

        df_sol_transfer.columns=["txhash","timestamp","action","from","to","amount","decimals","tokenaddress"]
        df_sol_transfer=df_sol_transfer.astype({
            "timestamp":int,
            "amount":float,
            "decimals":int,
        })
        
        time_min_df_token_transfer
        

        df_sol_transfer = df_sol_transfer.groupby(by=["txhash"],  group_keys=False).apply(lambda gdf: drop_ex_txhash(gdf))
        
 
        if(len(df_sol_transfer)==0):
            continue
        token_decimal  =  (df_sol_transfer["decimals"].tolist()[0])
        df_sol_transfer["amount"] = df_sol_transfer["amount"] / 10**token_decimal
        df_sol_transfer["amount"] = df_sol_transfer["amount"].round(2) 
        df_sol_transfer["datetime"] = pd.to_datetime(df_sol_transfer['timestamp'], unit='s')  
        df_sol_transfer = df_sol_transfer[["timestamp", "txhash", "datetime" ,"from","to","amount"]]     
        
        df_sol_transfer = df_sol_transfer.groupby(by = ["txhash","from","to" ],  group_keys=False).apply(lambda gdf: sum_same_tx_from_to(gdf))
        df_sol_transfer.to_csv(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source/find_depth/  "mid" /f"mid_sol_transfer_{str_dalaoaddress}.csv",index=False)
 
        df_sol_transfer = df_sol_transfer[[ "timestamp", "datetime", "from","to","amount"]]       
        df_sol_transfer = df_sol_transfer.groupby(by = [ "from","to" ],  group_keys=False).apply(lambda gdf: sum_same_from_to(gdf))
        
        df_sol_transfer["is_exend"] = 0
        df_sol_transfer["is_relationend"] = 0
        df_sol_transfer.loc[( df_sol_transfer["from"].isin(cur_arr_realtion_address) | df_sol_transfer["to"].isin(cur_arr_realtion_address)),"is_relationend"] = 1
 
        df_sol_transfer.loc[( df_sol_transfer["from"].isin(arr_exclude_address) | df_sol_transfer["to"].isin(arr_exclude_address)),"is_exend"] = 1
        
        
        df_sol_transfer=df_sol_transfer.sort_values(by="timestamp",ascending=False)
        df_sol_transfer.to_excel(baseclass.ana_dalao_relation_by_solscan_path /str_tokenaddress_dalao_source/find_depth/  "final"/f"sol_transfer_{str_dalaoaddress}.xlsx",index=False)
 
 
main()