import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright

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

with open("FacebookAutoPoster/post_content_ep1_short1.txt", "r", encoding="utf-8") as f:
    caption = f.read()

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")
    context = browser.contexts[0]
    page = context.pages[0]

    print("Target page URL:", page.url)

    # 1. Tìm ô textbox caption trong dialog
    textbox = page.locator("div[role='dialog'] div[role='textbox'][contenteditable='true']").first
    if textbox.is_visible():
        textbox.click()
        page.wait_for_timeout(500)
        # Chọn tất cả và xóa chữ "p"
        page.keyboard.press("Control+a")
        page.keyboard.press("Backspace")
        page.wait_for_timeout(500)

        # Gõ toàn bộ caption tiếng Anh
        print("Đang chèn caption tiếng Anh chuẩn SEO...")
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(2000)

    # Chụp ảnh kiểm tra trước khi bấm Post
    page.screenshot(path="FacebookAutoPoster/ready_to_post.png")
    print("Saved ready_to_post.png")

    # 2. Bấm nút Post
    post_btn = page.locator("div[role='dialog'] [aria-label='Post'], div[role='dialog'] [aria-label='Đăng']").first
    if not post_btn.is_visible():
        # Fallback nút có chữ Post
        post_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Post')").first

    print("Bấm nút Post...")
    post_btn.click()

    # 3. Chờ modal đóng lại (tải lên hoàn tất)
    print("Đang chờ xuất bản video...")
    for i in range(30):
        dialogs = page.locator("div[role='dialog']:has([aria-label='Post']), div[role='dialog']:has([aria-label='Đăng'])")
        if dialogs.count() == 0 or not dialogs.first.is_visible():
            print(f"Modal đã đóng sau {(i+1)*2} giây.")
            break
        page.wait_for_timeout(2000)

    page.wait_for_timeout(8000)

    # 4. Điều hướng về trang cá nhân để tự động bình luận link YouTube
    print("Đang truy cập trang cá nhân để bình luận link YouTube...")
    profile_url = "https://www.facebook.com/profile.php?id=61594841053758"
    page.goto(profile_url, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(6000)

    # Cuộn nhẹ xuống bài viết đầu tiên
    page.mouse.wheel(0, 500)
    page.wait_for_timeout(3000)

    # Tìm nút Comment trên bài viết đầu tiên
    print("Đang tìm nút bình luận...")
    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 comment_btn.is_visible():
        print("Clicking comment button...")
        comment_btn.click()
        page.wait_for_timeout(2000)

    # 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"]'
    ).last

    if comment_box.is_visible():
        comment_box.click()
        page.wait_for_timeout(500)
        print("Gõ bình luận link YouTube...")
        page.keyboard.insert_text(youtube_comment)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        print("Đã gửi bình luận!")
        page.wait_for_timeout(6000)

    # Chụp ảnh xác thực nghiệm thu
    ss_path = "FacebookAutoPoster/post_and_comment_verified.png"
    page.screenshot(path=ss_path)
    print(f"📸 Đã chụp ảnh xác thực tại: {ss_path}")
