import os
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')

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"
CAPTION_FILE = "FacebookAutoPoster/post_content_ep1_short2.txt"
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 open(CAPTION_FILE, "r", encoding="utf-8") as f:
    caption = f.read().strip()

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Kết nối Chrome CDP 9224 để hoàn tất đă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]

    # 1. Kiểm tra và click nút Continue nếu có modal "Review audience"
    continue_btn = page.locator("span:has-text('Continue'), div[role='dialog'] div[role='button']:has-text('Continue'), div[role='button']:has-text('Tiếp tục'), div[aria-label='Continue']").first
    if continue_btn.is_visible():
        print("🎯 Phát hiện popup 'Review audience' / 'Tiếp tục', đang click (force=True)...")
        continue_btn.click(force=True)
        page.wait_for_timeout(2000)
        # Nếu có nút Save / Lưu sau đó
        save_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Save'), div[role='dialog'] div[role='button']:has-text('Lưu')").first
        if save_btn.is_visible():
            save_btn.click(force=True)
            page.wait_for_timeout(2000)

    page.screenshot(path="FacebookAutoPoster/after_continue.png")
    print("📸 Đã chụp: after_continue.png")

    # 2. Định vị ô nhập caption trong Create post modal
    print("✍️ Đang định vị ô nhập caption...")
    textbox = page.locator("div[role='dialog'] div[role='textbox'][contenteditable='true']").first
    if not textbox.is_visible():
        textbox = page.locator("div[role='textbox'][contenteditable='true']").last

    if textbox.is_visible():
        try:
            textbox.focus()
            page.wait_for_timeout(300)
            textbox.click(force=True)
        except Exception:
            textbox.focus()
        page.wait_for_timeout(500)
        # Xóa text cũ nếu có
        page.keyboard.press("Control+a")
        page.keyboard.press("Backspace")
        page.wait_for_timeout(300)
        print("✍️ Đang chèn caption tiếng Anh...")
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(2000)
    else:
        print("⚠️ Không tìm thấy ô textbox trong dialog!")

    page.screenshot(path="FacebookAutoPoster/ready_to_click_post.png")
    print("📸 Đã chụp: ready_to_click_post.png")

    # 3. Bấm nút Post / Đăng
    print("🚀 Đang 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():
        post_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Post'), div[role='dialog'] div[role='button']:has-text('Đăng')").first

    if post_btn.is_visible():
        post_btn.click(force=True)
        print("✅ Đã click nút Post!")
    else:
        print("Gửi Ctrl+Enter để xuất bản...")
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")

    # Chờ modal xuất bản đóng lại
    print("⏳ Đang chờ Facebook xử lý và đóng modal (tối đa 40s)...")
    for _ in range(20):
        modal = page.locator("div[role='dialog']:has([aria-label='Đăng']), div[role='dialog']:has([aria-label='Post'])")
        if modal.count() == 0 or not modal.first.is_visible():
            print("✅ Modal tạo bài viết đã đóng hoàn tất!")
            break
        page.wait_for_timeout(2000)

    page.wait_for_timeout(8000)

    # 4. Điều hướng về trang cá nhân để kiểm tra và ghim comment link YouTube
    print(f"🔄 Đang mở trang cá nhân {PROFILE_URL} để tự động bình luận link YouTube 4K...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(5000)
    page.mouse.wheel(0, 500)
    page.wait_for_timeout(2000)

    # Tìm nút mở bình luận trên bài viết vừa đăng
    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():
        leave_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"][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():
        comment_box.click()
        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(5000)
        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 định vị được ô nhập bình luận trên bài viết mới nhất.")
        page.screenshot(path="FacebookAutoPoster/day2_comment_pending.png")
