import sys
import time
from playwright.sync_api import sync_playwright

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

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"
YOUTUBE_COMMENT = (
    "🎬 Watch the full Episode 2 battle documentary in 4K UHD on YouTube:\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]

    print("Navigating to profile...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded")
    page.wait_for_timeout(4000)

    # Cuộn nhẹ xuống khu vực bài viết
    page.mouse.wheel(0, 500)
    page.wait_for_timeout(2000)

    page.screenshot(path="FacebookAutoPoster/ep2_short1_timeline_check.png")
    print("📸 Saved: ep2_short1_timeline_check.png")

    # Tìm ô comment trên bài viết đầu tiên
    comment_box = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a comment'], div[role='textbox'][contenteditable='true'][aria-label*='comment']").first
    
    if not comment_box.is_visible():
        leave_btn = page.locator("div[role='button'][aria-label*='Leave a comment'], div[role='button'][aria-label*='Comment'], div[role='button'][aria-label*='Bình luận']").first
        if leave_btn.is_visible():
            leave_btn.click(force=True)
            page.wait_for_timeout(2000)
            comment_box = page.locator("div[role='textbox'][contenteditable='true']").first

    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("✍️ Gõ bình luận link YouTube Episode 2...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        page.wait_for_timeout(5000)
        print("🎉 Đã bình luận thành công link YouTube Episode 2!")

        page.screenshot(path="FacebookAutoPoster/ep2_short1_comment_done.png")
        print("📸 Saved: ep2_short1_comment_done.png")
    else:
        print("⚠️ Vẫn chưa tìm thấy ô comment, cuộn thêm...")
        page.mouse.wheel(0, 400)
        page.wait_for_timeout(2000)
        page.screenshot(path="FacebookAutoPoster/ep2_short1_scroll_debug.png")
