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()
    
    # 1. Fill University name: San Jose State University
    uni_input = page.locator("input[aria-label*='University name'], input[placeholder*='University name'], input[aria-label*='College'], input[placeholder*='College']").first
    if uni_input.count() == 0:
        # Fallback to finding the input inside the University card
        uni_input = page.locator("input[type='text'], input[type='search']").filter(has_not=page.locator("[aria-label='Search Facebook']")).first
        
    print('Filling University name...')
    uni_input.click()
    uni_input.fill('San Jose State University')
    page.wait_for_timeout(2000)
    
    # Select from dropdown
    uni_opts = page.locator("div[role='listbox'] div[role='option'], div[role='option'], ul[role='listbox'] li")
    print('Uni dropdown options count:', uni_opts.count())
    if uni_opts.count() > 0:
        print('Selecting option:', uni_opts.first.inner_text().replace('\n', ' '))
        uni_opts.first.click()
    else:
        page.keyboard.press('Enter')
    page.wait_for_timeout(1500)
    
    # 2. Check Graduated checkbox
    grad_cb = page.locator("input[type='checkbox']").first
    if grad_cb.count() > 0 and not grad_cb.is_checked():
        print('Checking Graduated checkbox...')
        grad_cb.check()
        page.wait_for_timeout(1000)
        
    # 3. Subject / Concentration
    subj_input = page.locator("input[aria-label*='Subject'], input[placeholder*='Subject']")
    if subj_input.count() > 0:
        print('Filling Subject...')
        subj_input.first.click()
        subj_input.first.fill('Film and Television Production')
        page.wait_for_timeout(1500)
        s_opts = page.locator("div[role='listbox'] div[role='option'], div[role='option']")
        if s_opts.count() > 0:
            s_opts.first.click()
        else:
            page.keyboard.press('Tab')
        page.wait_for_timeout(1000)
        
    # 4. Degree
    degree_input = page.locator("input[aria-label*='Degree'], input[placeholder*='Degree']")
    if degree_input.count() > 0:
        print('Filling Degree...')
        degree_input.first.click()
        degree_input.first.fill('Bachelor of Arts')
        page.wait_for_timeout(1000)
        page.keyboard.press('Tab')
        
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\edu_form_filled.png')
    
    # 5. Click Save
    save_btn = page.locator("div[role='button']:has-text('Save'), span:has-text('Save')").first
    print('Clicking Save...')
    save_btn.click()
    page.wait_for_timeout(5000)
    
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\edu_saved.png')
    print('Education saved successfully!')
