import sys
import time
from playwright.sync_api import sync_playwright

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

TARGETS = [
    "Ngân Thanh",
    "Loan Hong",
    "Uyên Phương",
    "Nguyễn Thy",
    "Lun Anh",
    "Uc Em",
    "GiAmanda Gill"
]

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

    confirmed = 0
    for name in TARGETS:
        name_el = page.locator(f"span:has-text('{name}')").first
        if name_el.count() > 0:
            print(f"🔍 Tìm thấy: {name}")
            # Tìm nút Confirm gần nhất đi kèm
            btn = name_el.locator("xpath=ancestor::div[.//div[@aria-label='Confirm']][1]//div[@aria-label='Confirm']").first
            if not btn.is_visible():
                btn = name_el.locator("xpath=ancestor::div[.//div[@role='button']][1]//div[text()='Confirm']").first

            if btn.is_visible():
                btn.click(force=True)
                confirmed += 1
                print(f"✅ Đã chấp nhận kết bạn: {name} (Avatar thật, có bạn chung)")
                page.wait_for_timeout(2000)
            else:
                print(f"⚠️ Không thấy nút Confirm của {name}")

    print(f"\n🎉 Tổng số bạn bè chất lượng vừa kết nạp: {confirmed}")
    page.screenshot(path="FacebookAutoPoster/quality_confirmed_live.png")
    print("📸 Saved: quality_confirmed_live.png")
