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

BIO_TEXT = "Filmmaker in California 🌴 Creator of @HistoryVault 4K historical docs 🇻🇳🇺🇸"
print(f"Target Bio: '{BIO_TEXT}' (Length: {len(BIO_TEXT)})")

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp('http://localhost:9222')
    context = browser.contexts[0]
    page = context.pages[0] if context.pages else context.new_page()
    
    url = 'https://www.facebook.com/profile.php?id=61594841053758&sk=directory_intro'
    page.goto(url, wait_until='domcontentloaded', timeout=30000)
    page.wait_for_timeout(3000)
    
    # 1. Open Bio editor if not already open
    textarea = page.locator('textarea')
    if textarea.count() == 0:
        print('Clicking About you button...')
        page.locator("div[role='button']:has-text('About you')").first.click()
        page.wait_for_timeout(2000)
        textarea = page.locator('textarea')
        
    if textarea.count() > 0:
        print('Filling Bio textarea...')
        textarea.first.fill('')
        textarea.first.fill(BIO_TEXT)
        page.wait_for_timeout(1000)
        
        # Click Save
        save_btn = page.locator("div[aria-label='Save'][role='button'], div[role='button']:has-text('Save'), span:has-text('Save')").first
        print('Clicking Save button...')
        save_btn.click()
        page.wait_for_timeout(4000)
        print('Bio saved successfully!')
        page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\bio_saved.png')
    else:
        print('ERROR: Textarea not found!')

    # 2. Inspect Pinned details
    print('\nLooking for Pinned details button...')
    pinned_btn = page.locator("div[role='button']:has-text('Pinned details')").first
    if pinned_btn.count() > 0:
        print('Clicking Pinned details button...')
        pinned_btn.click()
        page.wait_for_timeout(3000)
        page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\pinned_details_view.png')
        print('Saved pinned_details_view.png')
        
        # Check checkboxes or list items in dialog / panel
        checkboxes = page.locator("input[type='checkbox'], div[role='checkbox']")
        print('Total checkboxes in Pinned details:', checkboxes.count())
        for i in range(checkboxes.count()):
            cb = checkboxes.nth(i)
            parent = cb.locator("xpath=..")
            print(f"Checkbox [{i}]: checked={cb.is_checked() if cb.get_attribute('type')=='checkbox' else cb.get_attribute('aria-checked')} text='{parent.inner_text().replace(chr(10), ' ')}'")
            
        dialog = page.locator("div[role='dialog']")
        if dialog.count() > 0:
            print('=== PINNED DETAILS DIALOG TEXT ===')
            print(dialog.inner_text())
