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)
    
    # Locate the edit button near "Du học sinh"
    # Find all edit buttons or aria-label containing edit
    edit_btns = page.locator("div[aria-label*='Edit'], div[role='button'] i.x1b0d499, div[role='button']:has(svg)")
    print('Found edit candidates:', edit_btns.count())
    
    # Let's find the specific pencil button in the About You section
    about_card = page.locator("text=/Du học sinh/i").first
    # The pencil icon is a sibling or inside the same row
    pencil = page.locator("div[role='button']").filter(has=page.locator("i[data-visualcompletion='css-img'], svg")).all()
    print('Total icon buttons:', len(pencil))
    
    # Let's click the edit button via JS or click directly on the pencil near About You
    clicked = False
    # Using JS to find the button directly next to the About You text
    clicked = page.evaluate("""() => {
        const textEl = Array.from(document.querySelectorAll('*')).find(el => el.innerText && el.innerText.includes('Du học sinh'));
        if (!textEl) return 'Text not found';
        const container = textEl.closest('div[class*="x"]') || textEl.parentElement;
        const row = container.parentElement;
        const btn = row.querySelector('div[role="button"], [aria-label*="Edit"], [aria-label*="Chỉnh sửa"]');
        if (btn) {
            btn.click();
            return 'Clicked button';
        }
        return 'Button not found in row';
    }""")
    print('JS Click result:', clicked)
    page.wait_for_timeout(2000)
    
    # Check if textarea appeared
    textarea = page.locator('textarea')
    print('Textarea count:', textarea.count())
    if textarea.count() > 0:
        print('Filling English About You...')
        textarea.first.fill('')
        textarea.first.fill(ABOUT_YOU_EN)
        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
        if save_btn.count() > 0:
            save_btn.click()
            page.wait_for_timeout(4000)
            print('Saved About You successfully!')
        else:
            print('Save button not found!')
    else:
        print('Textarea did not appear')
        
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\after_update_about_details.png')
