import sys
import time
from playwright.sync_api import sync_playwright

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

youtube_comment = (
    "🎬 Watch the full Episode 1 documentary in 4K UHD on YouTube:\n"
    "👉 https://youtu.be/DT202N1I4-A\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]

    # Cuộn đến vị trí bài viết video
    page.goto("https://www.facebook.com/profile.php?id=61594841053758", wait_until="domcontentloaded")
    page.wait_for_timeout(4000)
    page.mouse.wheel(0, 750)
    page.wait_for_timeout(2000)

    # Tìm ô Write a comment đầu tiên (thuộc bài viết video mới nhất)
    comment_inputs = 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']")
    print("Found comment inputs count:", comment_inputs.count())

    if comment_inputs.count() > 0:
        first_box = comment_inputs.first
        first_box.click()
        page.wait_for_timeout(500)
        print("Đang gõ comment link YouTube vào bài video...")
        page.keyboard.insert_text(youtube_comment)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        print("Đã gửi comment thành công!")
        page.wait_for_timeout(5000)

    # Chụp ảnh xác thực bài đăng video có kèm comment link YouTube
    ss_path = "FacebookAutoPoster/video_post_with_youtube_comment.png"
    page.screenshot(path=ss_path)
    print(f"📸 Đã chụp ảnh xác thực tại: {ss_path}")
