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

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

VIDEO_PATH = str(Path("content/shorts/ep2_short_2.mp4").resolve())
print(f"Target video: {VIDEO_PATH}, Size: {os.path.getsize(VIDEO_PATH) / 1024 / 1024:.2f} MB")

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
    print("Create dialog is visible:", create_dialog.is_visible())

    # Find the video file input
    video_input = page.locator("input[type='file'][accept*='video']").first
    print("Found video input count:", video_input.count())

    if video_input.count() > 0:
        print("Setting input files on video input...")
        video_input.set_input_files(VIDEO_PATH)
        print("Waiting 10 seconds for Facebook to process video card...")
        time.sleep(10)
        page.screenshot(path="FacebookAutoPoster/after_video_input_set.png")
        print("Saved after_video_input_set.png")
