from playwright.sync_api import sync_playwright
import requests
import time
import random
import os

def get_keywords_from_url(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        keywords = response.text.strip().split('\n')
        return [kw.strip() for kw in keywords if kw.strip()]
    except Exception as e:
        print(f"Error fetching keywords: {e}")
        return []

def search_and_interact(playwright, keyword):
    chrome_path = "C:/Program Files/Google/Chrome/Application/chrome.exe"
    
    if not os.path.exists(chrome_path):
        print("Chrome executable not found. Please check the path.")
        return False

    browser = playwright.chromium.launch(
        executable_path=chrome_path,
        headless=False,
        args=['--disable-blink-features=AutomationControlled']
    )
    
    context = browser.new_context(
        user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
    )
    page = context.new_page()
    
    try:
        # Tìm kiếm trên Google
        search_query = f"{keyword} amazon"
        print(f"Searching Google with: {search_query}")
        page.goto("https://www.google.com", timeout=60000)
        page.fill('textarea[name="q"]', search_query)
        page.press('textarea[name="q"]', 'Enter')
        
        page.wait_for_selector('div#search', timeout=60000)
        time.sleep(5)
        
        if page.query_selector('form#captcha-form'):
            print("CAPTCHA detected. Cannot proceed automatically.")
            return False
        
        links = page.query_selector_all('a[href]')
        amazon_url = None
        
        print("Found URLs:")
        for link in links:
            url = link.get_attribute('href')
            if url:
                print(f"- {url}")
                if ("amazon.com" in url and 
                    "url=" not in url and 
                    "/search/" not in url and 
                    not url.startswith("https://www.google.com")):
                    amazon_url = url
                    break
        
        if not amazon_url:
            print("No valid Amazon product URL found after extended wait.")
            return False
        
        # Truy cập trang Amazon
        print(f"Accessing Amazon URL: {amazon_url}")
        page.goto(amazon_url, timeout=60000)
        time.sleep(3)  # Chờ trang tải cơ bản
        
        # Tương tác trong khoảng 5 phút
        print("Interacting with the page for ~5 minutes...")
        start_time = time.time()
        interaction_duration = 300  # 300 giây = 5 phút
        
        while time.time() - start_time < interaction_duration:
            action = random.choice([
                "scroll_down", "scroll_up", "click", "hover", "search"
            ])
            
            if action == "scroll_down":
                scroll_distance = random.randint(300, 1000)
                page.evaluate(f"window.scrollBy(0, {scroll_distance})")
                print(f"Scrolled down {scroll_distance}px")
                time.sleep(random.uniform(2, 5))  # Tăng từ 1-3 lên 2-5 giây
            
            elif action == "scroll_up":
                scroll_distance = random.randint(200, 800)
                page.evaluate(f"window.scrollBy(0, -{scroll_distance})")
                print(f"Scrolled up {scroll_distance}px")
                time.sleep(random.uniform(2, 5))
            
            elif action == "click":
                clickable_elements = page.query_selector_all('a, button, div[role="button"], span.clickable')
                if clickable_elements and random.random() > 0.3:
                    element = random.choice(clickable_elements)
                    try:
                        element.click()
                        print(f"Clicked on: {element.inner_text()[:50]}...")
                        time.sleep(random.uniform(3, 6))  # Tăng từ 1-4 lên 3-6 giây
                    except Exception as e:
                        print(f"Failed to click element: {e}")
            
            elif action == "hover":
                hoverable_elements = page.query_selector_all('a, img, div, span')
                if hoverable_elements:
                    element = random.choice(hoverable_elements)
                    try:
                        element.hover()
                        print(f"Hovered over: {element.inner_text()[:50] or 'an element'}...")
                        time.sleep(random.uniform(2, 5))
                    except Exception as e:
                        print(f"Failed to hover element: {e}")
            
            elif action == "search":
                search_box = page.query_selector('input#twotabsearchtextbox')
                if search_box and random.random() > 0.5:  # 50% cơ hội tìm kiếm
                    random_terms = ["related item", "accessories", "reviews", "similar"]
                    search_term = f"{keyword} {random.choice(random_terms)}"
                    search_box.fill(search_term)
                    print(f"Typed in search box: {search_term}")
                    time.sleep(random.uniform(2, 4))
                    if random.random() > 0.5:  # 50% cơ hội nhấn Enter
                        search_box.press("Enter")
                        print("Pressed Enter in search box")
                        time.sleep(random.uniform(3, 6))
            
            # Kiểm tra thời gian còn lại
            remaining_time = interaction_duration - (time.time() - start_time)
            if remaining_time < 5:
                break
        
        print(f"Total interaction time: {int(time.time() - start_time)} seconds")
        return True
    
    except Exception as e:
        print(f"Error processing {keyword}: {e}")
        return False
    
    finally:
        context.close()
        browser.close()

def main():
    keyword_url = "https://cuongphuckhanh.com/key.txt"
    keywords = get_keywords_from_url(keyword_url)
    
    if not keywords:
        print("No keywords found. Exiting...")
        return
    
    # Chọn ngẫu nhiên một từ khóa
    selected_keyword = random.choice(keywords)
    print(f"\nRandomly selected keyword: {selected_keyword}")
    
    with sync_playwright() as playwright:
        success = search_and_interact(playwright, selected_keyword)
        
        if success:
            print("Interaction completed successfully.")
        else:
            print("Failed to interact with the page.")

if __name__ == "__main__":
    main()