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

ABOUT_YOU_EN = (
    "Filmmaker & Content Creator based in California ☀️ Passionate about world history, "
    "cinematography, and Vietnamese heritage. Currently producing the 4K documentary "
    "series 'Forgotten Battles' on YouTube (History Vault) 🇻🇳🇺🇸"
)

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=about_details'
    page.goto(url, wait_until='domcontentloaded', timeout=30000)
    page.wait_for_timeout(3000)
    
    # Click button [8] aria='Edit'
    edit_btn = page.locator("div[role='main'] div[aria-label='Edit']").first
    print('Found Edit button. Clicking...')
    edit_btn.click()
    page.wait_for_timeout(2000)
    
    # Check for textarea
    textarea = page.locator("div[role='main'] textarea")
    print('Textarea count:', textarea.count())
    if textarea.count() > 0:
        print('Filling English About You text...')
        textarea.first.fill('')
        textarea.first.fill(ABOUT_YOU_EN)
        page.wait_for_timeout(1000)
        
        # Click Save
        save_btn = page.locator("div[role='main'] div[aria-label='Save'][role='button'], div[role='main'] div[role='button']:has-text('Save'), div[role='main'] span:has-text('Save')").first
        print('Clicking Save...')
        save_btn.click()
        page.wait_for_timeout(4000)
        print('Successfully saved English Details About You!')
    else:
        print('Textarea not found!')
        
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\details_after_save.png')
    print('Screenshot details_after_save.png saved')
