import sys
import time
from playwright.sync_api import sync_playwright

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

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🔍 Bắt đầu quét toàn bộ cập nhật mới trên Facebook Seven Nguyen...")

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

    # 1. Quét thông báo (Notifications)
    print("1️⃣ Mở trang chủ Facebook & kiểm tra thông báo...")
    page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    page.keyboard.press("Escape")
    time.sleep(1)

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

    bell = page.locator("[aria-label*='Notifications'], [aria-label*='Thông báo']").first
    if bell.is_visible():
        bell.click(force=True)
        time.sleep(2)
        page.screenshot(path="FacebookAutoPoster/scan_notifications.png")
        print("📸 Đã chụp thông báo: scan_notifications.png")

        items = page.locator("div[role='dialog'] a, div[role='dialog'] [role='listitem']").all()
        print(f"--- DANH SÁCH THÔNG BÁO MỚI ({len(items)} items) ---")
        for idx, it in enumerate(items[:12]):
            txt = it.inner_text().strip().replace('\n', ' ')
            if txt:
                print(f"[{idx}] {txt}")

    # Đóng menu thông báo
    page.keyboard.press("Escape")
    time.sleep(1)

    # 2. Quét Friend Requests
    print("\n2️⃣ Quét danh sách lời mời kết bạn...")
    page.goto("https://www.facebook.com/friends/requests", wait_until="domcontentloaded", timeout=30000)
    time.sleep(3)
    page.screenshot(path="FacebookAutoPoster/scan_friend_requests.png")
    print("📸 Đã chụp lời mời kết bạn: scan_friend_requests.png")

    header = page.locator("h1:has-text('Friend requests'), span:has-text('Friend requests'), span:has-text('Lời mời kết bạn')").first
    print("Header:", header.inner_text() if header.is_visible() else "None")

    # 3. Quét Profile cá nhân & tương tác các bài mới
    print(f"\n3️⃣ Mở trang cá nhân: {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.screenshot(path="FacebookAutoPoster/scan_profile_top.png")
    print("📸 Đã chụp đầu trang cá nhân: scan_profile_top.png")

    # Đọc số lượng bạn bè
    friends_el = page.locator("a[href*='friends']:has-text('friends'), a[href*='friends']:has-text('bạn bè')").first
    if not friends_el.is_visible():
        friends_el = page.locator("div:has-text('friends')").first
    print("Số lượng bạn bè hiển thị:", friends_el.inner_text().strip().replace('\n', ' ') if friends_el.count() > 0 else "N/A")

    # Cuộn xuống xem các bài đăng
    page.mouse.wheel(0, 450)
    time.sleep(2)
    page.screenshot(path="FacebookAutoPoster/scan_post1_cafe.png")
    print("📸 Đã chụp bài đăng Cafe: scan_post1_cafe.png")

    page.mouse.wheel(0, 600)
    time.sleep(2)
    page.screenshot(path="FacebookAutoPoster/scan_post2_video.png")
    print("📸 Đã chụp bài đăng Video Ep2: scan_post2_video.png")

print("✅ Hoàn tất toàn bộ quy trình quét cập nhật!")
