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"Testing with: {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]

    # Close any open dialogs first
    page.keyboard.press("Escape")
    time.sleep(1)
    page.keyboard.press("Escape")
    time.sleep(1)

    print("Navigating to profile...")
    page.goto("https://www.facebook.com/profile.php?id=61594841053758", wait_until="domcontentloaded")
    time.sleep(4)

    wom = page.locator("div[role='main'] div[role='button']:has-text(\"What's on your mind\"), div[role='button']:has-text(\"Bạn đang nghĩ gì\")").first
    if wom.is_visible():
        print("Clicking What's on your mind...")
        wom.click(force=True)
        time.sleep(2)

    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 visible:", create_dialog.is_visible())

    photo_btn = create_dialog.locator("div[role='button'][aria-label*='Photo/video'], div[role='button'][aria-label*='Ảnh/video']").first
    print("Photo button visible:", photo_btn.is_visible())

    with page.expect_file_chooser(timeout=7000) as fc_info:
        photo_btn.click(force=True)
    fc = fc_info.value
    print("✅ File chooser intercepted! Setting files...")
    fc.set_files(VIDEO_PATH)
    print("✅ FileChooser.set_files completed! Waiting 10s for video parsing...")
    time.sleep(10)

    page.screenshot(path="FacebookAutoPoster/test_fc_video_success.png")
    print("📸 Saved test_fc_video_success.png!")
