

import json


import shutil

import urllib.parse
from base_class import BaseVariableFunction
from base_class import *

old_print = print


def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)


print = timestamped_print
baseclass = BaseVariableFunction(__file__)
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
baseclass.makedirpath(baseclass.dalao_transaction_st_solanafm_path)

# Pump.fun  6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P

# Raydium_Authority_V4 = "5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1"
# WSOL_Token = "So11111111111111111111111111111111111111112"


def eheck_one_transaction_isswap(gdf, str_dalaoaddress):
    sign = gdf["sign"].tolist()[0]
    # if (sign == "2JBTiuHr1tpZ4abbwn4JP6vqm2CYmd1NoGjxkjPiv9y5MYan2D9NDsKTZMPw3fSzJegR64T8N1HcGUuZ45Jt3DWe"):
    #     print("gdf=", gdf)
    #     raise
    # 之前的是针对 raydium 平台并且 自己发送token/sol 自己接收token/sol
    # if gdf["source"].isin([Raydium_Authority_V4]).any() and gdf["destination"].isin([Raydium_Authority_V4]).any() and gdf["source"].isin([str_dalaoaddress]).any() and gdf["destination"].isin([str_dalaoaddress]).any():
    #     return gdf
    # 现在是自己发送token/sol 接收token/sol 不需要 raydium平台
    if gdf["source"].isin([str_dalaoaddress]).any() and gdf["destination"].isin([str_dalaoaddress]).any():
        return gdf
    else:
        return None


def get_multransaction_st():
    success_address_list = arr_str_dalaoaddress.copy()
    for idx in range(0, len(arr_str_dalaoaddress), batchSize):
        thread_list = []
        for cur_idx in range(idx, min(idx+batchSize, len(arr_str_dalaoaddress))):
            thread = threading.Thread(
                target=get_onetransaction_st,
                args=(arr_str_dalaoaddress[cur_idx],
                      success_address_list)
            )
            thread_list.append(thread)
        for thread in thread_list:
            thread.start()
        for thread in thread_list:
            thread.join()
        time.sleep(1)
    return


def get_onetransaction_st(str_dalaoaddress, success_address_list):
    print(f"enter {str_dalaoaddress}")
    try:
        # 不存在此dalao的文件 直接跳过
        if not (baseclass.dalao_transfer_solanafm_path/f"{str_dalaoaddress}.json").exists():
            return
        new_arr_obj_dalao_transaction = []
        with (baseclass.dalao_transfer_solanafm_path/f"{str_dalaoaddress}.json").open(mode='r') as f:
            arr_obj_dalao_transaction = json.load(f)
        # 构造新的结果 方便后续转为csv格式 
        # ori 为
            # {
            # "transactionHash": "53SSVoVwQwoBJCFg17WVoj1bis7xPXDx6LD88VHnNn3TDPKJwuCzBqcVvVw1DtRptf7WMdmCVijrdAC8UzxT7aas",
            # "data": [
            # {
            # "instructionIndex": -1,
            # "innerInstructionIndex": -1,
            # "action": "unknownTransfer",
            # "status": "Successful",
            # "source": "unknowned",
            # "sourceAssociation": null,
            # "destination": "2xgeeA8T9AkYKPh5k7zDTpVLWisSu7eou6opsGKjm5mr",
            # "destinationAssociation": null,
            # "token": "",
            # "amount": 326931586,
            # "timestamp": 1720643298
            # },
            # xxxx
            # }
        # 新的结构为
        # new_arr_obj_dalao_transaction [
        # sign:"xxxx"
        # "instructionIndex": -1,
        # "innerInstructionIndex": -1,
        # "action": "unknownTransfer",
        # "status": "Successful",
        # "source": "unknowned",
        # "sourceAssociation": null,
        # "destination": "2xgeeA8T9AkYKPh5k7zDTpVLWisSu7eou6opsGKjm5mr",
        # "destinationAssociation": null,
        # "token": "",
        # "amount": 326931586,
        # "timestamp": 1720643298
        # ]

        for obj_dalao_transaction in arr_obj_dalao_transaction:
            sign = obj_dalao_transaction["transactionHash"]
            arr_obj_instruction_data = obj_dalao_transaction["data"]
            for obj_instruction_data in arr_obj_instruction_data:
                # if (obj_instruction_data["instructionIndex"] == -1):
                #     continue
                if (obj_instruction_data["status"] != "Successful"):
                    continue
                if (obj_instruction_data["action"] in ["transfer", "transferChecked","unknownTransfer"]
                    # and ((obj_instruction_data["source"] in [Raydium_Authority_V4, str_dalaoaddress])
                    #     or (obj_instruction_data["destination"] in [Raydium_Authority_V4, str_dalaoaddress]))):
                    and ((obj_instruction_data["source"] in [ str_dalaoaddress])
                        or (obj_instruction_data["destination"] in [ str_dalaoaddress]))):
                    obj_instruction_data["sign"] = sign
                    new_arr_obj_dalao_transaction.append(obj_instruction_data)

                else:
                    continue

        df = pd.DataFrame(new_arr_obj_dalao_transaction)
        if (len(df) == 0):
            df = pd.DataFrame(
                columns=["timestamp", "sign", "source", 
                        "destination", "token", "amount"
                        "instructionIndex", "innerInstructionIndex"
                        ])
        df = df[["timestamp", "sign",  "source",
                "destination", "token", "amount",
                    "instructionIndex", "innerInstructionIndex"
                ]]

        df = df.groupby(by=["sign"]).apply(
            lambda gdf: eheck_one_transaction_isswap(gdf, str_dalaoaddress))
        if (len(df) == 0):
            df = pd.DataFrame(
                columns=["timestamp", "sign", "source",
                         "destination", "token", "amount",
                          "instructionIndex", "innerInstructionIndex"
                         
                         ])
        df.to_csv(baseclass.dalao_transaction_st_solanafm_path /
                f"{str_dalaoaddress}.csv", index=False)

        success_address_list.remove(str_dalaoaddress)
        print(f"{str_dalaoaddress} success remainder= {len(success_address_list)} \n", end='')
    except Exception as e:
        print(f"error_str_dalaoaddress={str_dalaoaddress} ",e)
        raise
# 9XvTzh7udehQMaQLikViwfXa5GpiDU4spw6BZYppsNJn 调用另一个router 对于raydium pool 进行交换


df = pd.read_excel(baseclass.dalao_total_ana_fm_path /
                   "anaing_dalao.xlsx", dtype=object)

arr_str_dalaoaddress = df["add"].tolist()
arr_str_dalaoaddress.append(baseclass.mywalletaddress)

# arr_str_dalaoaddress=arr_str_dalaoaddress[0:10]
batchSize = 170
get_multransaction_st()
print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
