import os
import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright

video_file = str(Path(r'C:\Projects\Historical\content\shorts\ep2_short_1.mp4').resolve())
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 Chrome on localhost:9222...")
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://localhost:9222")
    page = browser.contexts[0].pages[0]
    
    # Quay lại trang chủ Facebook
    print("Navigating to https://www.facebook.com/ ...")
    page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=30000)
    page.wait_for_timeout(4000)
    
    # Click icon 'Photo/video'
    print("Finding Photo/video trigger...")
    # Thử tìm theo aria-label hoặc hình ảnh photo/video
    photo_triggers = page.locator("[aria-label*='Photo/video'], [aria-label*='Ảnh/video'], div:has-text('Photo/video')")
    
    # Dùng expect_file_chooser để bắt sự kiện chọn file chuẩn của trình duyệt
    print("Clicking photo/video trigger and selecting file...")
    with page.expect_file_chooser(timeout=10000) as fc_info:
        # Nếu có nút Photo/video
        btn = page.locator("div[role='button']:has(img[src*='photo']), [aria-label*='Photo/video'], [aria-label*='Ảnh/video']").first
        if btn.is_visible():
            btn.click()
        else:
            # Click vào ô xanh lá cây cạnh input
            page.locator("text=/What's on your mind|Bạn đang nghĩ gì/i").first.click()
            page.wait_for_timeout(2000)
            page.locator("[aria-label*='Photo/video'], [aria-label*='Ảnh/video']").first.click()
            
    file_chooser = fc_info.value
    print("Selecting video file:", video_file)
    file_chooser.set_files(video_file)
    print("File attached! Waiting 10s for upload preview...")
    page.wait_for_timeout(10000)
    
    # Điền caption
    print("Entering caption...")
    textbox = page.locator("div[role='textbox'][contenteditable='true']").last
    if textbox.is_visible():
        textbox.click()
        page.wait_for_timeout(500)
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(3000)
        
    page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\step2_video_ready.png")
    print("Screenshot step2_video_ready.png saved!")
    
    # Bấm nút Post
    print("Clicking Post button...")
    post_btn = page.locator("div[aria-label='Post'], div[aria-label='Đăng'], button:has-text('Post'), button:has-text('Đăng')").first
    if post_btn.is_visible():
        post_btn.click(timeout=10000)
    else:
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")
        
    print("Posted! Waiting 15s for processing...")
    page.wait_for_timeout(15000)
    page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\step3_finished.png")
    print("Done!")
