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]

    # Find span or div with text "Save changes"
    el = page.locator("span:text-is('Save changes'), div:text-is('Save changes')").first
    print("Element visible:", el.is_visible())
    if el.is_visible():
        el.click(force=True)
        print("Clicked Save changes! Waiting 6s...")
        time.sleep(6)
    else:
        # Fallback: look for aria-label or contains
        el2 = page.locator("[aria-label*='Save changes'], [aria-label*='Lưu thay đổi']").first
        if el2.is_visible():
            el2.click(force=True)
            print("Clicked via aria-label! Waiting 6s...")
            time.sleep(6)

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