import sys
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')
    context = browser.contexts[0]
    page = context.pages[0] if context.pages else context.new_page()
    page.goto('https://www.facebook.com/', wait_until='domcontentloaded')
    page.wait_for_timeout(3000)

    links = page.locator('a[href*="/groups/"]')
    print(f'Total group links found: {links.count()}')
    for i in range(links.count()):
        try:
            txt = links.nth(i).inner_text().strip().replace('\n', ' - ')
            href = links.nth(i).get_attribute('href')
            if txt and ('hội' in txt.lower() or 'sinh viên' in txt.lower() or 'california' in txt.lower() or 'du học' in txt.lower() or 'history' in txt.lower()):
                print(f'Match [{i}]: text="{txt}" | href="{href}"')
            elif txt:
                print(f'Item [{i}]: text="{txt}" | href="{href}"')
        except Exception:
            pass
