import sys
import time
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"

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

    # Close any open dialogs first
    page.keyboard.press("Escape")
    time.sleep(1)

    print(f"Navigating to {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)

    # Click What's on your mind
    wom = page.locator("div[role='main'] div[role='button']:has-text(\"What's on your mind\"), div[role='button']:has-text(\"Bạn đang nghĩ gì\")").first
    if wom.is_visible():
        wom.click(force=True)
        time.sleep(2)

    create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
    print("Create dialog is visible:", create_dialog.is_visible())

    # List all inputs
    inputs = page.locator("input[type='file']").all()
    print(f"Found {len(inputs)} file inputs:")
    for i, inp in enumerate(inputs):
        acc = inp.get_attribute("accept")
        multiple = inp.get_attribute("multiple")
        cls = inp.get_attribute("class")
        print(f"Input {i}: accept={acc}, multiple={multiple}, class={cls}")

    # List buttons inside dialog
    btns = create_dialog.locator("div[role='button']").all()
    print(f"Found {len(btns)} buttons in dialog:")
    for i, b in enumerate(btns):
        al = b.get_attribute("aria-label")
        txt = b.inner_text().strip().replace('\n', ' ')
        if al or txt:
            print(f"Button {i}: aria-label={repr(al)}, text={repr(txt)}")

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