import sys
import time
import random
from playwright.sync_api import sync_playwright

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

comment_text = "Visual và tone màu hoài niệm đẹp quá anh. Đoạn bến nước sương khói nhìn có chất điện ảnh ghê. Nghe giữa trưa thấy tĩnh tâm hẳn. Chúc anh một ngày an lành nhé!"

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] if context.pages else context.new_page()

    # Tìm ô nhập bình luận thứ hai (thuộc bài viết của Anthony Wilson)
    comment_inputs = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a public comment'], div[role='textbox'][contenteditable='true'][aria-label*='Viết bình luận công khai']")
    
    print(f"Số ô comment tìm thấy: {comment_inputs.count()}")
    if comment_inputs.count() >= 2:
        target_box = comment_inputs.nth(1)
        target_box.scroll_into_view_if_needed()
        page.wait_for_timeout(1000)
        
        # Di chuột tự nhiên vào ô nhập
        box_rect = target_box.bounding_box()
        if box_rect:
            page.mouse.move(box_rect['x'] + 20, box_rect['y'] + 10, steps=8)
            time.sleep(0.3)
            page.mouse.click(box_rect['x'] + 20, box_rect['y'] + 10)
        else:
            target_box.click()

        page.wait_for_timeout(800)

        # Mô phỏng gõ phím con người
        print(f"Seven Nguyen đang gõ comment: '{comment_text}'...")
        for char in comment_text:
            page.keyboard.insert_text(char)
            time.sleep(random.uniform(0.03, 0.09))

        page.wait_for_timeout(1500)
        print("Đang phát lệnh gửi bình luận (Enter)...")
        page.keyboard.press("Enter")
        page.wait_for_timeout(5000)

        # Chụp ảnh xác thực bình luận đã hiển thị trên bài viết
        ss_path = "FacebookAutoPoster/anthony_post_commented.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 đủ ô comment.")
