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")
    context = browser.contexts[0]
    
    page = None
    for p_item in context.pages:
        if "facebook.com" in p_item.url:
            page = p_item
            break
            
    if not page:
        page = context.pages[0]
        
    page.bring_to_front()
    print("Tab:", page.title())
    
    # 1. Kiểm tra xem modal 'Create post' đã mở chưa
    modal = page.locator("div[role='dialog']").first
    if not modal.is_visible():
        print("Mở modal tạo bài viết...")
        composer_trigger = page.locator("text=/What's on your mind|Bạn đang nghĩ gì/i").first
        if composer_trigger.is_visible():
            composer_trigger.click()
        else:
            page.keyboard.press("p")
        page.wait_for_timeout(4000)
    else:
        print("Modal 'Create post' đã mở sẵn.")
        
    page.wait_for_timeout(3000)
    
    # 2. Đính kèm video file
    print("Đang tìm input file để nạp video...")
    file_inputs = page.locator("input[type='file']")
    print("Số lượng file input tìm thấy:", file_inputs.count())
    
    if file_inputs.count() > 0:
        print("Đang nạp file video:", video_file)
        file_inputs.first.set_input_files(video_file)
        page.wait_for_timeout(7000)
    else:
        photo_btn = page.locator("[aria-label*='Photo/video'], [aria-label*='Ảnh/video']").first
        if photo_btn.is_visible():
            print("Click nút Ảnh/Video...")
            with page.expect_file_chooser() as fc_info:
                photo_btn.click()
            fc = fc_info.value
            fc.set_files(video_file)
            page.wait_for_timeout(7000)
            
    # 3. Điền Caption
    print("Đang gõ 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(2000)
    else:
        print("Textbox chưa sẵn sàng, click vào giữa modal...")
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(2000)
        
    # Chụp ảnh kiểm tra trước khi bấm đăng
    page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\step2_video_attached.png")
    print("Đã chụp step2_video_attached.png")
    
    # 4. Chờ video xử lý và bấm Đăng
    print("Đang chờ nút Post kích hoạt...")
    page.wait_for_timeout(5000)
    
    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():
        print("Bấm nút Post...")
        post_btn.click(timeout=10000)
        print("✅ Đã bấm nút Post!")
    else:
        print("Gửi phím tắt Ctrl+Enter để đăng...")
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")
        print("✅ Đã gửi lệnh Ctrl+Enter!")
        
    print("Đang đợi Facebook lưu và đăng video (15s)...")
    page.wait_for_timeout(15000)
    page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\step3_posted.png")
    print("Đã chụp step3_posted.png. Hoàn thành!")
