from playwright.sync_api import sync_playwright

GROUP_URL = "https://www.facebook.com/groups/1928282657363211/"

with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=False,
        args=["--disable-blink-features=AutomationControlled"],
    )
    context = browser.new_context(
        storage_state="storage_state.json",
        viewport={"width": 1366, "height": 900},
        user_agent=(
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
        ),
    )
    page = context.new_page()
    page.goto(GROUP_URL, wait_until="networkidle")
    page.wait_for_timeout(3000)

    for _ in range(3):
        page.mouse.wheel(0, 2500)
        page.wait_for_timeout(1500)

    articles = page.locator('div[aria-posinset]')
    count = articles.count()
    print(f"Talált poszt-konténerek: {count}")

    with open("links_dump.txt", "w", encoding="utf-8") as f:
        for i in range(count):
            art = articles.nth(i)
            f.write(f"\n===== POST #{i} =====\n")
            links = art.locator("a")
            lcount = links.count()
            for j in range(lcount):
                link = links.nth(j)
                try:
                    href = link.get_attribute("href", timeout=500) or ""
                    text = link.inner_text(timeout=500).strip().replace("\n", " ")[:40]
                    aria = link.get_attribute("aria-label", timeout=500) or ""
                except Exception:
                    continue
                if href:
                    f.write(f"  [{j}] text='{text}' aria='{aria[:40]}' href={href}\n")

    browser.close()
    print("Kész, lásd links_dump.txt")
