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_1.mp4").resolve())
print(f"Target video: {VIDEO_PATH}")

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

    print("1. Going to facebook.com...")
    page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    page.keyboard.press("Escape")
    time.sleep(1)

    print("2. Clicking 'What's on your mind'...")
    wom = page.locator("[aria-label*=\"What's on your mind\"], [aria-label*=\"Bạn đang nghĩ gì\"]").first
    if wom.is_visible():
        wom.click()
        time.sleep(2)
    else:
        print("wom not visible, pressing p...")
        page.keyboard.press("p")
        time.sleep(2)

    page.screenshot(path="FacebookAutoPoster/test_wom_opened.png")

    print("3. Looking for input[type='file']...")
    file_inputs = page.locator("input[type='file']").all()
    print(f"Found {len(file_inputs)} file inputs.")
    
    if file_inputs:
        print("Injecting video file into input[type='file']...")
        file_inputs[0].set_input_files(VIDEO_PATH)
        print("File injected! Waiting 10s for video preview to load...")
        time.sleep(10)
    else:
        print("No file input found directly, looking for Photo/video button...")
        photo_btn = page.locator("div[role='dialog']:has-text('Create post') [aria-label*='Photo/video']").first
        if photo_btn.is_visible():
            photo_btn.click()
            time.sleep(2)
            file_inputs = page.locator("input[type='file']").all()
            print(f"Found {len(file_inputs)} file inputs after clicking photo btn.")
            if file_inputs:
                file_inputs[0].set_input_files(VIDEO_PATH)
                time.sleep(10)

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