import sys
import time
from playwright.sync_api import sync_playwright

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🔍 Bắt đầu quét và duyệt lời mời kết bạn uy tín...")

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    # Navigate to friend requests
    print("Điều hướng tới https://www.facebook.com/friends/requests...")
    page.goto("https://www.facebook.com/friends/requests", wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.keyboard.press("Escape")
    time.sleep(1)

    page.screenshot(path="FacebookAutoPoster/requests_before_accept.png")
    print("📸 Saved: FacebookAutoPoster/requests_before_accept.png")

    # Tìm danh sách các card lời mời kết bạn
    # Thường nằm trong div[role='main'] hoặc thẻ div chứa nút Confirm
    confirm_buttons = page.locator("div[aria-label='Confirm'], div[role='button']:has-text('Confirm'), div[role='button']:has-text('Xác nhận')").all()
    print(f"Tìm thấy {len(confirm_buttons)} nút Confirm trên trang.")

    # Tìm các thẻ người dùng để kiểm tra chi tiết
    cards = page.locator("div[role='listitem'], a[href*='/user/'], a[href*='profile.php']").all()
    print(f"Tìm thấy các phần tử liên quan: {len(cards)}")

    # Lấy danh sách tên và thông tin trực quan
    # Quét qua các vùng chứa nút Confirm
    accepted_count = 0
    # Quét tối đa 8 requests an toàn mỗi đợt để giữ profile tự nhiên
    for i in range(min(len(confirm_buttons), 10)):
        # Lấy lại danh sách nút để tránh stale element
        btns = page.locator("div[aria-label='Confirm'], div[role='button']:has-text('Confirm'), div[role='button']:has-text('Xác nhận')").all()
        if not btns:
            break
        btn = btns[0]
        
        # Tìm container cha của nút này
        parent = btn.locator("xpath=./ancestor::div[contains(@class, 'x1n2onr6') or contains(@role, 'listitem') or string-length(text()) > 5][4]")
        text_info = parent.inner_text().strip().replace('\n', ' -- ') if parent.count() > 0 else ""
        print(f"\n--- Request #{i+1} ---")
        print(f"Thông tin: {text_info[:180]}")

        # Kiểm tra avatar trong container cha
        imgs = parent.locator("image, img").all()
        has_real_avatar = True
        for img in imgs:
            src = img.get_attribute("src") or img.get_attribute("xlink:href") or ""
            # Silhouette / default avatars thường chứa các chuỗi rác
            if "silhouette" in src.lower() or "null" in src.lower() or not src:
                has_real_avatar = False
                break
        
        print(f"Ảnh đại diện hợp lệ: {has_real_avatar}")
        
        # Nếu không có dấu hiệu clone bất thường, chấp nhận
        if has_real_avatar:
            print("👉 Bấm Confirm...")
            btn.click(force=True)
            accepted_count += 1
            time.sleep(2.5)
        else:
            print("⚠️ Bỏ qua tài khoản này vì nghi ngờ clone không có avatar.")

    print(f"\n✅ Đã chấp nhận thành công {accepted_count} lời mời kết bạn uy tín!")
    time.sleep(3)
    page.screenshot(path="FacebookAutoPoster/requests_after_accept.png")
    print("📸 Saved: FacebookAutoPoster/requests_after_accept.png")
