import sys
import time
from playwright.sync_api import sync_playwright

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

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

    # Kiểm tra Messenger
    print("Checking Messenger...")
    msg_btn = page.locator('div[role="button"][aria-label*="Messenger"]').first
    if msg_btn.is_visible():
        msg_btn.click()
        page.wait_for_timeout(3000)
        page.screenshot(path="FacebookAutoPoster/messenger_opened.png")
        dialog = page.locator("div[role='dialog']")
        if dialog.count() > 0:
            print("Messenger content:\n", dialog.inner_text()[:400])
        page.keyboard.press("Escape")
        page.wait_for_timeout(1000)

    # Kiểm tra Notifications
    print("Checking Notifications...")
    notif_btn = page.locator('div[role="button"][aria-label*="Notifications"], div[role="button"][aria-label*="Thông báo"]').first
    if notif_btn.is_visible():
        notif_btn.click()
        page.wait_for_timeout(3000)
        page.screenshot(path="FacebookAutoPoster/notifs_20plus.png")
        dialog = page.locator("div[role='dialog']")
        if dialog.count() > 0:
            print("Notifications content:\n", dialog.inner_text()[:600])
        page.keyboard.press("Escape")
        page.wait_for_timeout(1000)
