import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"
IMAGE_PATH = str(Path("FacebookAutoPoster/lifestyle_media/seven_coastal_highway1.jpg").resolve())

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    # 1. Bấm Cancel ở banner cover photo nếu đang hiện
    cancel_btn = page.locator("div[role='button']:has-text('Cancel'), div[aria-label='Cancel']").first
    if cancel_btn.is_visible():
        print("Bấm Cancel ở cover photo banner...")
        cancel_btn.click(force=True)
        time.sleep(2)

    # 2. Click vào What's on your mind
    print("Clicking 'What\\'s on your mind?'...")
    wom = page.locator("span:has-text(\"What's on your mind?\")").first
    if not wom.is_visible():
        wom = page.locator("div[role='button']:has-text(\"What's on your mind?\")").first
    wom.click(force=True)
    time.sleep(3)

    page.screenshot(path="FacebookAutoPoster/test_wom_dialog_opened.png")
    print("📸 Saved: FacebookAutoPoster/test_wom_dialog_opened.png")

    dialog = page.locator("div[role='dialog']").first
    print("Dialog visible:", dialog.is_visible())
    if dialog.is_visible():
        print("Dialog text snippet:", dialog.inner_text()[:300].replace('\n', ' '))
