
# from datetime import datetime, timezone
# from playwright.async_api import async_playwright, Playwright
# from playwright.sync_api import expect
from playwright.async_api import Playwright, async_playwright, expect
import random
import time
import datetime
import asyncio
import pathlib
import shutil
import inspect

def custom_print(*args, **kwargs):
    # 获取当前调用的行号
    frame = inspect.currentframe().f_back
    line_no = frame.f_lineno
    # 获取文件名
    # filename = frame.f_code.co_filename
    
    # 打印行号和文件名
    print(f"[{line_no}]", *args, **kwargs)

# 示例用法
custom_print("Hello, world!")
 
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)



 
baseclass.makedirpath(baseclass.dalao_ori_pnl_gmgn_path)
 
old_print = print
 

def timestamped_print(*args, **kwargs):

    frame = inspect.currentframe().f_back
    line_no = frame.f_lineno
    # 获取文件名
    # filename = frame.f_code.co_filename
    
    # 打印行号和文件名
    # print(f"[{line_no}]", *args, **kwargs)
    
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0),f"[:{line_no}]", *args, **kwargs)


print = timestamped_print
print('\n'*5)

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


number_chars_arr = ["k", "m", "b", "t", "p"]

number_chars_obj = {
    "k": 3,
    "m": 6,
    "b": 9,
    "t": 12,
    "p": 15
}
  


activities_columns = ['tokenaddress', 'tokenname',  'last_active', 
                      'profit_eth',   'profit_percent', 'buy_eth',
                        'sell_eth', '30d_txns_buy','30d_txns_sell', 
                        'is_warning' ]

 
async def check_tbody_isfull(page ,str_dalaoaddress):
    table = page.locator('div[aria-labelledby="tabs-leftTabs--tab-0"]')
    tbody_ = table.locator(
        'tbody')
    arr_trs = await tbody_.locator('tr').all()
    print( f"{str_dalaoaddress} arr_trs len =", len(arr_trs))
    if len(arr_trs)>=200:
        return True
    if len(arr_trs)==0:
        return False

    last_tr = arr_trs[-1]
    arr_tds = await last_tr.locator('td').all()
    p_token_last_active =  arr_tds[0].locator("p")
    str_token_last_active =( await p_token_last_active.text_content()).strip()
    if "--"   in str_token_last_active :
        return True
    
    if "d" not in str_token_last_active :
        return False
    str_token_last_active=str_token_last_active.replace("d","")
    number_token_last_active =  int(str_token_last_active)
    print( f" {str_dalaoaddress} number_token_last_active =",   (number_token_last_active))
    if number_token_last_active>360:
        return True
    else :
        return False
     

async def do_some_thing(playwright, cur_arr_str_dalaoaddress, cur_arr_str_dalaoUrl):
    global dalao_len


    # browser =  playwright.chromium.launch(headless=True)
    context = await playwright.chromium.launch_persistent_context(user_data_dir=USER_DIR_PATH, accept_downloads=True, headless=False)
    # context = await playwright.firefox.launch_persistent_context(user_data_dir=USER_DIR_PATH , headless=False)
    # context = await playwright.chromium.launch_persistent_context(user_data_dir=USER_DIR_PATH , headless=False)
    # context = browser.new_context()
    context.set_default_timeout(28000)
    await asyncio.sleep(17)
    # context = await browser.new_context()
    arr_page = [None]*dalao_len
    
    global set_str_dalaoaddress
    arr_str_dalaoaddress = cur_arr_str_dalaoaddress
    arr_str_dalaoUrl = cur_arr_str_dalaoUrl
    
    for str_dalaoaddress_idx in range(0, len(arr_str_dalaoaddress) , dalao_len):
        cur_arr_str_dalaoaddress = []
        cur_arr_str_dalaoUrl = []
        
        for idx_dalao  in range(0 ,dalao_len ):
            if str_dalaoaddress_idx + idx_dalao  >= len(arr_str_dalaoaddress):
                continue
            temp_str_dalaoaddress = arr_str_dalaoaddress[str_dalaoaddress_idx + idx_dalao ]
            temp_str_dalaoUrl = arr_str_dalaoUrl[str_dalaoaddress_idx +  idx_dalao ]
            cur_arr_str_dalaoaddress.append( temp_str_dalaoaddress )
            cur_arr_str_dalaoUrl.append( temp_str_dalaoUrl )
        

        # tasks = [handle_one_page(
        #    idx_page,context, arr_page, cur_arr_str_dalaoaddress[idx_page] , cur_arr_str_dalaoUrl[idx_page] ) for idx_page in range(0, dalao_len)]
        # await asyncio.gather(*tasks)

        tasks_for_wait = [asyncio.create_task(handle_one_page(
           idx_page,context, arr_page, cur_arr_str_dalaoaddress[idx_page] , cur_arr_str_dalaoUrl[idx_page] ) ) for idx_page in range(0, len(cur_arr_str_dalaoaddress))]

        # 获取 交易token较少的        
        # done, pending = await asyncio.wait(tasks_for_wait, timeout=60)
        done, pending = await asyncio.wait(tasks_for_wait, timeout=300)
        # for page in arr_page:
        #     if page is not None:
        #         print(f"do_some_thing  close")
        #         await page.close()
    
    await asyncio.sleep(3)
    await context.close()
async def handle_one_page( idx_page,context, arr_page, str_dalaoaddress , str_dalaoUrl ):
    global set_str_dalaoaddress
    page = None
    try:
        arr_page[idx_page] = await context.new_page()
        await   arr_page[idx_page].goto(str_dalaoUrl, timeout=29000)
        page =  arr_page[idx_page]
        sleep_time = random.randint(10,20)
        sleep_time=sleep_time/10
        await asyncio.sleep(5)

        await asyncio.sleep(sleep_time)
        
        table = page.locator('div[aria-labelledby="tabs-leftTabs--tab-0"]')
        thead_ = table.locator( 'thead')    
        arr_th =   await thead_.locator('th').all() 
        print('arr_th=',arr_th)
        await asyncio.sleep(115)

        # th_balance = arr_th[4]  
        
        text_th_balance =await th_balance.text_content()
        print('text_th_balance=',text_th_balance)
        
        if "USD" in text_th_balance:
            div_sol = th_balance.locator('div:nth-child(2)')
            text_div_sol =await div_sol.text_content()
            print(f"text_div_sol= {text_div_sol}")
            await  div_sol.click()
        await asyncio.sleep(15)
 
 
        prev_page_height = await page.evaluate(
            "document.documentElement.scrollHeight")
        while True:
            isfull = await check_tbody_isfull(page=page , str_dalaoaddress=str_dalaoaddress)
            if isfull:
                break
            await page.evaluate(
                "window.scrollTo(0, document.body.scrollHeight);")
            await asyncio.sleep(2)
            await page.evaluate(
                "window.scrollTo(0, document.body.scrollHeight);")
            await asyncio.sleep(3)
            cur_page_height = await page.evaluate(
                "document.documentElement.scrollHeight")
            print(f"prev_page_height={prev_page_height} cur_page_height={cur_page_height}  ")
            if cur_page_height > prev_page_height:
                prev_page_height = cur_page_height
            elif cur_page_height == prev_page_height:
                break
        tbody_data = None
        while True:
            try:
                tbody_data = await get_tbody_data(page=page, str_dalaoaddress=str_dalaoaddress)
            except Exception as e: 
                print(traceback.format_exc())
                await asyncio.sleep(2)
                raise
            if tbody_data is None:
                await asyncio.sleep(0.8)
                raise("tbody_data is None")
            else:
                break
        dalao_df = pd.DataFrame(
            tbody_data, columns=activities_columns)
        dalao_df.to_csv(baseclass.dalao_ori_pnl_gmgn_path /
                f"ori_gmgn_pnl_{str_dalaoaddress}.csv", index=False)
        set_str_dalaoaddress.discard(str_dalaoaddress)

    except Exception as e:
        print("handle_one_page error",e)
        raise
    if page is not None:
        print(f"str_dalaoaddress= {str_dalaoaddress} close")
        await page.close()



async def get_tbody_data(page, str_dalaoaddress):
    arr_tokenlink = None
    listen_tr_ = None
    listen_td_ = None
   
    try:
        print(f"enter {str_dalaoaddress} get_tbody_data")
        table = page.locator('div[aria-labelledby="tabs-leftTabs--tab-0"]')
         
        tbody_ = table.locator( 'tbody')  
    
    
        await asyncio.sleep(3)
        arr_trs = await tbody_.locator('tr').all()
        arr_trs=arr_trs[0:200]
        arr_trs_datares = []
        flag_end = False
        for idx_tr_ in range(0, len(arr_trs)):
            
            if flag_end == True :
                break
            if(idx_tr_ %20==0):
                print(f"get_tbody_data {str_dalaoaddress} {idx_tr_}")
            arr_tds_datares = [None]*10
            arr_trs_datares.append(arr_tds_datares)


            tr_ = arr_trs[idx_tr_]
            listen_tr_ = tr_
            arr_tds = await tr_.locator('td').all()
            is_warning = 0
            # 共有10列 
            # 'Token/Last Active', 'Unrealized',  '30D Realized Profit', 
            #           'Total Profit',  'Balance',   
            #           'Position %',  'Bought', 
            #             'Sold',   '30D TXs','Ahare'
            for idx_td_ in range(0, len(arr_tds)):
                td_ = arr_tds[idx_td_]
                listen_td_ =td_
                if (idx_td_ == 0):
                    # Token/Last Active
                    arr_tokenlink = await td_.locator("a").all()
                    href_tokenaddress_name = await  arr_tokenlink[0].get_attribute('href')
                    href_tokenaddress = href_tokenaddress_name.strip().split(
                        '/token/')[-1]
                    # arr_tokenaddress_name = href_tokenaddress_name.split("?symbol=")
                    str_tokenaddress = href_tokenaddress  
                    
                    div_title = td_.locator('div[title]')
                    str_tokenname = "unknown"
                    if (await div_title.count()) == 0:
                        str_tokenname = str_tokenname + "_"+str_tokenaddress[0:4]
                    else:  
                        str_tokenname = await div_title.get_attribute('title')
                    str_tokenname = re.sub(r'[^!-~]', '', str_tokenname)
                    str_tokenname = str_tokenname.replace(",","")
                    if str_tokenname=="":
                        str_tokenname = "unknown" +"_"+str_tokenaddress[0:4]
     
                    p_token_last_active =   td_.locator("p")
                                       
                    str_token_last_active = (await p_token_last_active.text_content()).strip()
                    if str_token_last_active == "--":
                        flag_end = True
                        arr_trs_datares.pop()
                        break
                    
                    if "min"   in str_token_last_active  or  "h" in str_token_last_active or  "s" in str_token_last_active:
                        str_token_last_active = "0d"
                    temp_str_token_last_active=str_token_last_active.replace("d","")
                    number_token_last_active =  int(temp_str_token_last_active)
                   
                    if number_token_last_active > 45:
                        flag_end = True
                        arr_trs_datares.pop()
                        break
                    
                    g_warning =   td_.locator('g[clip-path="url(#clip0_6068_12422)"]')
                    if (await g_warning.count()) != 0:
                        is_warning = 1
        
                    arr_tds_datares[0] = str_tokenaddress
                    arr_tds_datares[1] = str_tokenname
                    arr_tds_datares[2] = str_token_last_active
                    
                     
                elif (idx_td_ == 1):
                    continue
               
                elif (idx_td_ == 2):
                    continue
           
                elif (idx_td_ == 3):
                    # 'Total Profit'
                    
                    arr_p_profit =  await td_.locator('p').all()
                    str_profit_sol = (await arr_p_profit[0].text_content()).strip().lower()
                    str_profit_percent = (await arr_p_profit[1].text_content()).strip().lower()
                    if "$" in str_profit_sol:
                        raise Exception("$ in Total Profit")
                    
                    str_profit_sol =  re.sub(r'[sol,%\+><]', "", str_profit_sol)
                    str_profit_sol=str_profit_sol.strip()
                    str_profit_percent =  re.sub(r'[sol,%\+><]', "", str_profit_percent)
                    str_profit_percent=str_profit_percent.strip()
                    
      
                    if str_profit_sol=="--":
                        str_profit_sol = "0"
                        
                    if str_profit_percent=="--":
                        str_profit_percent = "0"
      
                    for str_number_char in number_chars_arr  :
                        if str_number_char in str_profit_sol:
                            str_profit_sol=str_profit_sol.replace( str_number_char  ,"")
                            str_profit_sol = float(str_profit_sol) * 10 ** number_chars_obj[str_number_char]
                            str_profit_sol = str(str_profit_sol)
                        if str_number_char in str_profit_percent:
                            str_profit_percent=str_profit_percent.replace( str_number_char  ,"")
                            str_profit_percent = float(str_profit_percent) * 10 ** number_chars_obj[str_number_char]
                          
                            str_profit_percent = str(str_profit_percent)
                                
                
                    arr_tds_datares[3] = str_profit_sol
                    arr_tds_datares[4] = str(  round ( ( float(str_profit_percent) /100),2)   )
                    if is_warning ==1:
                        arr_tds_datares[4]="-1"
                        
 
                elif (idx_td_ == 4):
                    # balance
                    continue
      
                elif (idx_td_ == 5):
                    # Position
                    continue
    
                elif (idx_td_ == 6):
                    # bought
                    arr_p_buy =  await td_.locator('p').all()
                    str_buy_sol = (await arr_p_buy[0].text_content()).strip().lower()
                    if "$" in str_buy_sol:
                        raise Exception("$ in Bought")
                    
                    str_buy_sol =  re.sub(r'[sol,%\+><]', "", str_buy_sol)
                    str_buy_sol=str_buy_sol.strip()
                
                    for str_number_char in number_chars_arr  :
                        if str_number_char in str_buy_sol:
                            str_buy_sol=str_buy_sol.replace( str_number_char  ,"")
                            number_buy_sol = float(str_buy_sol) * 10 ** number_chars_obj[str_number_char]
                            str_buy_sol = str(number_buy_sol)
           
                    arr_tds_datares[5] = str_buy_sol
                    
                   
                elif (idx_td_ == 7):
                    # sold
                    arr_p_sell =  await td_.locator('p').all()
                    str_sell_sol = (await arr_p_sell[0].text_content()).strip().lower()
                    str_sell_sol =  re.sub(r'[sol,%\+><]', "", str_sell_sol)
                    str_sell_sol=str_sell_sol.strip()
                    
                    for str_number_char in number_chars_arr :
                        if str_number_char in str_sell_sol:
                            str_sell_sol=str_sell_sol.replace( str_number_char  ,"")
                            str_sell_sol = float(str_sell_sol) * 10 ** number_chars_obj[str_number_char]
                            str_sell_sol = str(str_sell_sol)
                            
                    arr_tds_datares[6] = str_sell_sol
                    
                elif (idx_td_ == 8):
                    #30d txns
                    
                    str_30d_txns= (await td_.text_content()).strip()
               
                    str_30d_txns =  re.sub(r'[\s,><]', "", str_30d_txns)
          
                    arr_30dtxns = str_30d_txns.split("/")
                    str_buy_txns = arr_30dtxns[0]
                    str_sell_txns =arr_30dtxns[1]
                    
                    for str_number_char in number_chars_arr :
                        if str_number_char in str_buy_txns:
                            str_buy_txns=str_buy_txns.replace( str_number_char  ,"")
                            str_buy_txns = float(str_buy_txns) * 10 ** number_chars_obj[str_number_char]
                            str_buy_txns = str(str_buy_txns)

                        if str_number_char in str_sell_txns:
                                str_sell_txns=str_sell_txns.replace( str_number_char  ,"")
                                str_sell_txns = float(str_sell_txns) * 10 ** number_chars_obj[str_number_char]
                                str_sell_txns = str(str_sell_txns)
							
                    arr_tds_datares[7] = str_buy_txns
                    arr_tds_datares[8] = str_sell_txns
                    arr_tds_datares[9] = is_warning

                                 
        return arr_trs_datares

    except Exception as e:
        print("error e= ",e)
        # print( "error",str_dalaoaddress, "listen_tr_=",(await listen_tr_.text_content()), 
        #       "listen_td_=",  (await listen_td_.text_content()) 
        #       )
        print( "error",str_dalaoaddress,  
              "listen_td_=",  (await listen_td_.text_content()) 
              )
                
        raise


async def get_onedriver_swapactivities(cur_arr_str_dalaoaddress, cur_arr_str_dalaoUrl):
    async with async_playwright() as playwright:
       
        await do_some_thing(playwright, cur_arr_str_dalaoaddress, cur_arr_str_dalaoUrl)


async def main():
    print("enter main()")
  
    await  get_onedriver_swapactivities( arr_str_dalaoaddress   , arr_str_dalaoUrl )  
        
 
    



df =  pd.read_excel( baseclass.dalao_merge_path / f"merge.xlsx", dtype=object)

arr_str_dalaoaddress = df['dalaoaddress'].drop_duplicates().tolist()

temp_arr_dalaoaddress = copy.deepcopy(arr_str_dalaoaddress)
for str_dalaoaddress in temp_arr_dalaoaddress:
    if (baseclass.dalao_ori_pnl_gmgn_path /
            f"ori_gmgn_pnl_{str_dalaoaddress}.csv").exists():
        arr_str_dalaoaddress.remove(str_dalaoaddress)

    

arr_str_dalaoaddress = [
    "6P4aHkv7oTbwMK6P57sVsejE52jNFeEvYhQMEBpNNN1U",
    "JD38n7ynKYcgPpF7k1BhXEeREu1KqptU93fVGy3S624k",
    "3oY1k7u6Gw49QMatX3cgmcMdpxqeY9MnCGAazEQANnPt"
]
arr_str_dalaoUrl = [
f"https://gmgn.ai/sol/address/{str_dalaoaddress}" for str_dalaoaddress in arr_str_dalaoaddress]

print('arr_str_dalaoaddress', len(arr_str_dalaoaddress))
 

set_str_dalaoaddress = set(arr_str_dalaoaddress)

 

dalao_len = 1
USER_DIR_PATH =  baseclass.browsercookie_path 
baseclass.makedirpath(USER_DIR_PATH)
asyncio.run(main())


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

