import sys
import os
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/ep1_short_1.mp4").resolve())
print("Video path:", video_path)

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    context = browser.contexts[0]
    page = None
    for pg in context.pages:
        if "facebook.com" in pg.url:
            page = pg
            break
    if not page:
        page = context.new_page()
        page.goto("https://www.facebook.com/", wait_until="domcontentloaded")
        page.wait_for_timeout(3000)

    page.bring_to_front()
    print("Page URL:", page.url)

    # Đóng dialog nếu đang mở
    page.keyboard.press("Escape")
    page.wait_for_timeout(1000)

    # Click What's on your mind
    print("Clicking What's on your mind...")
    whats_on_mind = page.locator("[aria-label*=\"What's on your mind\"], [aria-label*=\"Bạn đang nghĩ gì\"]:not([role='dialog'] *)").first
    if whats_on_mind.is_visible():
        whats_on_mind.click()
        page.wait_for_timeout(3000)
    else:
        page.keyboard.press("p")
        page.wait_for_timeout(3000)

    page.screenshot(path="FacebookAutoPoster/composer_opened.png")
    print("Saved composer_opened.png")

    # Kiểm tra các nút trong dialog
    dialog = page.locator("div[role='dialog']")
    print("Dialog count:", dialog.count())

    # Tìm nút Photo/video
    photo_btn = page.locator("div[role='dialog'] [aria-label*='Photo/video'], div[role='dialog'] [aria-label*='Ảnh/video']").first
    print("Photo/video button visible:", photo_btn.is_visible())

    # Thử set_input_files
    print("Trying set_input_files on dialog file inputs...")
    file_inputs = page.locator("div[role='dialog'] input[type='file']")
    print("Dialog file inputs count:", file_inputs.count())

    if file_inputs.count() > 0:
        page.set_input_files("div[role='dialog'] input[type='file']", video_path)
        print("✅ Successfully called page.set_input_files on dialog file input!")
    elif photo_btn.is_visible():
        print("Clicking photo_btn and setting input...")
        with page.expect_file_chooser() as fc_info:
            photo_btn.click()
        fc = fc_info.value
        fc.set_files(video_path)
        print("✅ Successfully set files via file chooser!")

    page.wait_for_timeout(5000)
    page.screenshot(path="FacebookAutoPoster/video_attached.png")
    print("Saved video_attached.png")
