import sys
import time
from playwright.sync_api import sync_playwright

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

YOUTUBE_COMMENT = (
    "🎬 Experience the full naval warfare in 4K UHD:\n"
    "👉 https://youtu.be/FKPhXdwFbII\n\n"
    "Subscribe to @thehistoricalvault-z9 for weekly 4K historical releases!"
)

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

    # Find the comment box right below the video post
    comment_box = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a comment'], div[role='textbox'][contenteditable='true'][aria-label*='Viết bình luận']").first
    if not comment_box.is_visible():
        comment_box = page.locator("div[role='textbox'][contenteditable='true']").first

    print("Comment box visible:", comment_box.is_visible())
    if comment_box.is_visible():
        comment_box.click(force=True)
        time.sleep(0.5)
        print("Typing YouTube 4K link comment...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        time.sleep(1.5)
        page.keyboard.press("Enter")
        print("🚀 Comment submitted! Waiting 5s...")
        time.sleep(5)

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