import sys
import time
from playwright.sync_api import sync_playwright

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

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

    page.goto("https://www.facebook.com/friends/requests", wait_until="domcontentloaded", timeout=30000)
    time.sleep(3)

    page.screenshot(path="FacebookAutoPoster/friend_requests_new.png")
    print("Saved friend_requests_new.png")

    cards = page.locator("div[role='listitem']").all()
    print(f"Found {len(cards)} friend request cards.")

    for i, card in enumerate(cards):
        text = card.inner_text().replace('\n', ' | ')
        # Check avatar img
        img = card.locator("img").first
        img_src = img.get_attribute("src") if img.is_visible() else "None"
        is_clone = "rsrc.php" in img_src or "silhouette" in img_src or img_src == "None"
        print(f"Card {i}: {text} | Avatar: {'CLONE/EMPTY' if is_clone else 'REAL PHOTO'}")

        if not is_clone and ("Confirm" in text or "Xác nhận" in text):
            confirm_btn = card.locator("div[role='button']:has-text('Confirm'), div[role='button']:has-text('Xác nhận')").first
            if confirm_btn.is_visible():
                print(f"👉 Accepting authentic request: {text.split('|')[0]}")
                confirm_btn.click(force=True)
                time.sleep(1.5)

    time.sleep(2)
    page.screenshot(path="FacebookAutoPoster/friend_requests_after_accept.png")
    print("Saved friend_requests_after_accept.png")
