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]

    # Look for elements around the top right of the cover photo
    # Let's inspect elements via JavaScript
    info = page.evaluate("""() => {
        const buttons = Array.from(document.querySelectorAll('*')).filter(el => 
            el.textContent && el.textContent.includes('Save changes') && el.children.length === 0
        );
        return buttons.map(b => ({
            tag: b.tagName,
            text: b.textContent,
            rect: b.getBoundingClientRect()
        }));
    }""")
    print("Found matching elements:", info)

    if info:
        x = info[0]['rect']['x'] + info[0]['rect']['width'] / 2
        y = info[0]['rect']['y'] + info[0]['rect']['height'] / 2
        print(f"Clicking at ({x}, {y})...")
        page.mouse.click(x, y)
        time.sleep(5)
    else:
        # Fallback coordinate click: the blue button in 1000x800 viewport is near x=910, y=65
        print("Fallback click at (910, 65)...")
        page.mouse.click(910, 65)
        time.sleep(5)

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