from playwright.sync_api import sync_playwright

caption = '''🔥 300 CHIẾN THUYỀN XIÊM RỢP BÓNG SÔNG TIỀN (1785) | Forgotten Battles Ep 2

50.000 quân xâm lược cùng hạm đội chiến thuyền trang bị đại bác phương Tây rầm rộ tiến vào phương Nam. Liệu vùng đất Gia Định có thể đứng vững trước sức mạnh hủy diệt này?

👉 Xem trọn vẹn diễn biến trận chiến bản 4K UHD tại bình luận đầu tiên!

#HistoryVault #UntoldBattles #NguyenHue #AncientWarfare #NavalBattles #LichSuVietNam #1785War'''

print('Connecting to finalize post...')
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp('http://localhost:9222')
    page = browser.contexts[0].pages[0]
    
    # 1. Đóng tooltip/sub-dialog nếu có
    page.keyboard.press('Escape')
    page.wait_for_timeout(1000)
    
    # 2. Click vào ô nhập caption
    print('Clicking textbox and typing caption...')
    textbox = page.locator('div[role=\"textbox\"][contenteditable=\"true\"]').first
    if textbox.is_visible():
        textbox.click()
        page.wait_for_timeout(500)
        page.keyboard.insert_text(caption)
    else:
        # Fallback click
        page.locator('text=/What\'s on your mind/i').first.click()
        page.wait_for_timeout(500)
        page.keyboard.insert_text(caption)
        
    page.wait_for_timeout(2000)
    page.screenshot(path='C:/Projects/Historical/FacebookAutoPoster/final_ready_to_post.png')
    print('Ready screenshot captured!')
    
    # 3. Bấm nút Post
    print('Clicking Post button...')
    post_btn = page.locator('div[aria-label=\"Post\"], div[role=\"button\"]:has-text(\"Post\")').last
    if post_btn.is_visible():
        post_btn.click()
        print('Post button clicked!')
    else:
        page.keyboard.down('Control')
        page.keyboard.press('Enter')
        page.keyboard.up('Control')
        print('Ctrl+Enter pressed!')
        
    page.wait_for_timeout(10000)
    page.screenshot(path='C:/Projects/Historical/FacebookAutoPoster/final_published.png')
    print('Published screenshot captured!')
