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

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_work'
    page.goto(url, wait_until='domcontentloaded', timeout=30000)
    page.wait_for_timeout(3000)
    
    # Click "Work experience" if form is not already open
    if page.locator("input[aria-label='Company']").count() == 0:
        print('Clicking Work experience button...')
        page.locator("div[role='button']:has-text('Work experience'), span:has-text('Work experience')").first.click()
        page.wait_for_timeout(2000)
        
    print('Filling Company: History Vault...')
    comp_input = page.locator("input[aria-label='Company']").first
    comp_input.click()
    comp_input.fill('History Vault')
    page.wait_for_timeout(1000)
    # If dropdown appears, select or press enter
    page.keyboard.press('Enter')
    page.wait_for_timeout(1000)
    
    print('Filling Position: Founder & Video Producer...')
    pos_input = page.locator("input[aria-label='Position']").first
    pos_input.click()
    pos_input.fill('Founder & Video Producer')
    page.wait_for_timeout(1000)
    page.keyboard.press('Enter')
    page.wait_for_timeout(1000)
    
    print('Filling City/Town: San Jose, California...')
    city_input = page.locator("input[aria-label='City/Town']").first
    city_input.click()
    city_input.fill('San Jose, California')
    page.wait_for_timeout(2000)
    # Check if dropdown with San Jose, California appears
    dropdown_opt = page.locator("ul[role='listbox'] li, div[role='option']").first
    if dropdown_opt.count() > 0:
        print('Clicking dropdown option:', dropdown_opt.inner_text().replace('\n', ' '))
        dropdown_opt.click()
    else:
        page.keyboard.press('Enter')
    page.wait_for_timeout(1000)
    
    print('Filling Description...')
    desc = page.locator("textarea").first
    if desc.count() > 0:
        desc.fill('Producing high-impact 4K historical animation documentaries.')
    
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\work_before_save.png')
    
    print('Clicking Save button...')
    save_btn = page.locator("div[role='button']:has-text('Save'), span:has-text('Save')").first
    save_btn.click()
    page.wait_for_timeout(5000)
    
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\work_after_save.png')
    print('Work saved! Screenshot work_after_save.png saved.')
