import pandas as pd
import json
import os
import time
arr_json_data = []
 
 
obj_example =    {
        "address": "EZZk361QgZDMx52AmMyc4NjFkuaNrdegwAxrLEbeaR94",
        "account_address": "8FzF2vcsNDBinao1wDTKDKLN7SeV6HLH1uduRfRtL3XT",
        "addr_type": 0,
        "amount_cur": 0,
        "usd_value": 0,
        "cost_cur": 0,
        "sell_amount_cur": 34148763.167781,
        "sell_amount_percentage": 1,
        "sell_volume_cur": 6449.83054886525,
        "buy_volume_cur": 1501.4988493578628,
        "buy_amount_cur": 34148763.167781,
        "netflow_usd": -4948.331699507387,
        "netflow_amount": 0,
        "buy_tx_count_cur": 9,
        "sell_tx_count_cur": 77,
        "wallet_tag_v2": "TOP1",
        "native_balance": "805755934855",
        "balance": 0,
        "profit": 4928.853565607387,
        "realized_profit": 4928.853565607387,
        "profit_change": 3.240583927213684,
        "amount_percentage": 0,
        "unrealized_profit": 0,
        "unrealized_pnl": None,
        "avg_cost": 0.000043969347937453594,
        "avg_sold": 0.00018887449941234176,
        "accu_amount": 0,
        "accu_cost": 0,
        "cost": 0,
        "total_cost": 1520.976983257863,
        "transfer_in": False,
        "is_new": False,
        "is_suspicious": False,
        "start_holding_at": 1742168061,
        "end_holding_at": 1742172930,
        "last_active_timestamp": 1742172930,
        "native_transfer": {
            "name": None,
            "from_address": "AxiomRYAid8ZDhS1bJUAzEaNSr69aTWB9ATfdDLfUbnc",
            "timestamp": 1741555940
        },
        "tags": [
            "sandwich_bot"
        ],
        "maker_token_tags": [],
        "name": None,
        "avatar": None,
        "twitter_username": None,
        "twitter_name": None,
        "created_at": 1738980654
    }
    
token_add= '2ZoJVM15fbbDgo6s5cTTX2Sj8V4sJ47rimb7gQhGpump'
arr_store_keys = [
         "address",
        "sell_amount_cur",
        "buy_amount_cur",

        
        "buy_tx_count_cur",
        "sell_tx_count_cur",
 
        "profit",
        "realized_profit",
        "profit_change",
        "avg_cost",
        "avg_sold",
        "start_holding_at",
        "end_holding_at",
        "tags",
]

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

    global arr_file,token_add  , arr_json_data
    arr_file = []
 
    with open(f'top_trader_gmgn_{token_add}.json', 'r',encoding='utf8') as f:
        old_arr_json_data = json.load(f)
 
    
    for obj in old_arr_json_data:
        filtered_obj = {}
        # 遍历obj的每一个value 元素，如果元素是数组或者obj，就删除这个key，否则就保留这个key
        for key, value in obj.items():
            if key in arr_store_keys:
                if key=='tags':
                    value = set(value) - set(['bullx' , 'photon','trojan','pepeboost','gmgn'])
                    filtered_obj[key] = "_".join(value)
                
                else:    
                    filtered_obj[key] = value
            else:
                continue
                
                
        arr_json_data.append(filtered_obj)
    
    return
                
import pytz
def utc_2_shanghaidate(df , utc_time_col ):
# 将字符串转换为UTC时间的datetime对象
    # df[utc_time_col] = pd.to_datetime(df[utc_time_col], utc=True)
    # 定义UTC+8时区
    utc_plus_8 = pytz.timezone('Asia/Shanghai')
    # 转换为UTC+8时间
    df[utc_time_col] = df[utc_time_col].dt.tz_localize('UTC')
    # # 提取时间字符串
    # df['shanghai_date'] = df['shanghai_date'].dt.strftime('%Y-%m-%d %H:%M')
    df[utc_time_col] = df[utc_time_col].dt.tz_convert(utc_plus_8)
    # 提取时间字符串
    df[utc_time_col] = df[utc_time_col].dt.strftime('%Y-%m-%d %H:%M')
    return df

 

def arr_json_2_df():
    global arr_json_data
    df  = pd.DataFrame(arr_json_data)
    # print(df)
    df['sell_token_amount'] = df['sell_amount_cur']  / 1e6
    df['buy_token_amount'] = df['buy_amount_cur']  / 1e6
    
    df['buy_tx_count'] = df['buy_tx_count_cur']  
    df['sell_tx_count'] = df['sell_tx_count_cur']  
    # 将价格转化为是市值 xxxK的市值
    df['avg_cost_mc'] = df['avg_cost'] *( 1e3 * 1e6/1e3) 
    df['avg_sold_mc'] = df['avg_sold'] *( 1e3 * 1e6 / 1e3)
    
    df['duration'] = (df['end_holding_at'] - df['start_holding_at'] )/60/60
    
    df["start_datetime"] = pd.to_datetime(df["start_holding_at"], unit='s'  )
    df = utc_2_shanghaidate(df, "start_datetime")

    df["end_datetime"] = pd.to_datetime(df["end_holding_at"], unit='s' )
    
    df = utc_2_shanghaidate(df, "end_datetime")
    
    
    df["gmgn"] = df.apply(lambda ser: makeurl(
    f"https://gmgn.ai/sol/token/{token_add}?tab=activity&maker={ser['address']}" , "gmgn" ), axis=1)
    df["beizhu"] = None
    df =df [[       "address",
        "buy_token_amount",
        "sell_token_amount",

        "buy_tx_count_cur",
        "sell_tx_count_cur",
        
        # "profit",
        "realized_profit",
        "profit_change" ,
        "avg_cost_mc",
        "avg_sold_mc",
        "start_datetime",
        "end_datetime" ,
    
        "duration",
            "tags",
        "gmgn",
        "beizhu"
        ]]
    df =df.round(1)
 

    
    df =df.sort_values(by=['realized_profit'], ascending=False)
    
 
    df.to_excel(f'top_trader_gmgn_{token_add}_{int(time.time())}.xlsx',index=False)
 


get_handle_json_top_trader()
arr_json_2_df()