import sys
sys.stdout.reconfigure(encoding='utf-8')
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp('http://localhost:9222')
    context = browser.contexts[0]
    page = context.pages[0]
    
    # Inspect elements with text 'No'
    els = page.locator("text='No'")
    print('Total elements with No:', els.count())
    for i in range(els.count()):
        el = els.nth(i)
        box = el.bounding_box()
        tag = el.evaluate("e => e.tagName")
        parent_tag = el.evaluate("e => e.parentElement.tagName")
        role = el.evaluate("e => e.getAttribute('role') || e.parentElement.getAttribute('role')")
        print(f"[{i}] tag={tag} parentTag={parent_tag} role={role} box={box}")
        if box and box['width'] > 50:
            print(f"Clicking element [{i}] at center ({box['x'] + box['width']/2}, {box['y'] + box['height']/2})...")
            page.mouse.click(box['x'] + box['width']/2, box['y'] + box['height']/2)
            page.wait_for_timeout(2000)
            break
            
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\after_dismiss_no.png')
