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]
    
    # 1. Click "No" on Share on Feed prompt if present
    no_btn = page.locator("div[role='button']:has-text('No'), span:has-text('No')")
    if no_btn.count() > 0:
        print('Dismissing Share on feed prompt...')
        no_btn.first.click()
        page.wait_for_timeout(1500)
        
    # 2. Click Home town button
    print('Clicking Home town button...')
    home_btn = page.locator("div[role='button']:has-text('Home town'), span:has-text('Home town')").first
    home_btn.click()
    page.wait_for_timeout(2000)
    
    # 3. Fill Home town input
    home_input = page.locator("input[placeholder*='Home town'], input[aria-label*='Home town'], input[placeholder*='hometown']").first
    if home_input.count() == 0:
        home_input = page.locator("div[role='main'] input[type='text'], div[role='main'] input[type='search']").first
        
    print('Typing Ho Chi Minh City, Vietnam...')
    home_input.click()
    home_input.fill('Ho Chi Minh City, Vietnam')
    page.wait_for_timeout(2000)
    
    # Select from dropdown
    opts = page.locator("div[role='listbox'] div[role='option'], div[role='option'], ul[role='listbox'] li")
    print('Hometown options count:', opts.count())
    if opts.count() > 0:
        print('Selecting:', opts.first.inner_text().replace('\n', ' '))
        opts.first.click()
    else:
        page.keyboard.press('Enter')
    page.wait_for_timeout(1500)
    
    # 4. 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(3000)
    
    # Dismiss feed prompt if it appears
    no_btn2 = page.locator("div[role='button']:has-text('No'), span:has-text('No')")
    if no_btn2.count() > 0:
        no_btn2.first.click()
        page.wait_for_timeout(1500)
        
    page.screenshot(path=r'C:\Projects\Historical\FacebookAutoPoster\hometown_saved.png')
    print('Finished finish_hometown.py!')
