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 complete Episode 1 in 4K UHD on YouTube:\n"
    "👉 https://youtu.be/DT202N1I4-A\n\n"
    "Subscribe to @thehistoricalvault-z9 for weekly 4K historical releases!"
)

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ✍️ Bắt đầu ghim link bình luận YouTube 4K vào bài đăng Day 2...")
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 để ô comment hiển thị rõ ràng
    page.mouse.wheel(0, 300)
    page.wait_for_timeout(1500)

    # Tìm ô comment đầu tiên trên trang (chính là bài Day 2 mới đăng)
    comment_box = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a comment'], div[role='textbox'][contenteditable='true'][aria-label*='comment']").first
    print("Comment box visible:", comment_box.is_visible())

    if comment_box.is_visible():
        try:
            comment_box.focus()
            page.wait_for_timeout(300)
            comment_box.click(force=True)
        except Exception:
            comment_box.focus()

        page.wait_for_timeout(500)
        print("✍️ Đang gõ bình luận...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        page.wait_for_timeout(5000)
        print("✅ Đã phát lệnh gửi bình luận thành công!")

        # Chụp ảnh xác thực
        ss_path = "FacebookAutoPoster/day2_post_with_youtube_comment.png"
        page.screenshot(path=ss_path)
        print(f"📸 Đã lưu ảnh xác thực tại: {ss_path}")
    else:
        print("⚠️ Không tìm thấy ô comment.")
