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 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!"
)

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

    # Mở profile nếu chưa mở
    if PROFILE_URL not in page.url:
        page.goto(PROFILE_URL, wait_until="domcontentloaded")
        page.wait_for_timeout(3000)

    # Cuộn nhẹ xuống để xem bài viết vừa đăng
    page.mouse.wheel(0, 600)
    page.wait_for_timeout(2000)

    # Chụp ảnh bài viết vừa đăng
    page.screenshot(path="FacebookAutoPoster/day2_post_published_check.png")
    print("📸 Đã chụp: day2_post_published_check.png")

    # Mở comment nếu cần
    leave_comment_btn = page.locator(
        'div[role="button"][aria-label*="Leave a comment"], '
        'div[role="button"][aria-label*="Bình luận"], '
        'div[role="button"][aria-label*="Comment"]'
    ).first

    if leave_comment_btn.is_visible():
        try:
            leave_comment_btn.click(force=True)
            page.wait_for_timeout(2000)
        except Exception:
            pass

    # Tìm ô nhập bình luận
    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"], '
        'div[role="textbox"][contenteditable="true"][aria-label*="comment"], '
        'div[role="textbox"][contenteditable="true"][aria-label*="bình luận"]'
    ).first

    if not comment_box.is_visible():
        comment_box = page.locator('div[role="textbox"][contenteditable="true"]').last

    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 link YouTube...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        page.wait_for_timeout(4000)
        print("✅ Đã bình luận thành công link YouTube vào bài đăng Day 2!")

        ss_path = "FacebookAutoPoster/day2_post_and_comment_verified.png"
        page.screenshot(path=ss_path)
        print(f"📸 Đã chụp ảnh xác thực tại: {ss_path}")
    else:
        print("⚠️ Không tìm thấy ô nhập bình luận.")
