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"
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')}] 🎯 Bắt đầu điền caption và bấm Post ngay lập tức...")
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    # Tìm ô textbox trong Create post dialog
    textbox = page.locator("div[role='dialog'] div[role='textbox'][contenteditable='true']").first
    print("Textbox visible:", textbox.is_visible())
    
    if textbox.is_visible():
        try:
            textbox.focus()
            page.wait_for_timeout(300)
            textbox.click(force=True)
        except Exception as e:
            print(f"Focus exception: {e}")
            textbox.focus()
            
        page.wait_for_timeout(500)
        # Clear existing text if any
        page.keyboard.press("Control+a")
        page.keyboard.press("Backspace")
        page.wait_for_timeout(300)
        
        print("✍️ Đang gõ caption...")
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(1000)
        
        # Đóng hashtag suggestion nếu có
        page.keyboard.press("Escape")
        page.wait_for_timeout(1000)
        print("✅ Đã gõ xong caption!")

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

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

    print("Post button visible:", post_btn.is_visible())
    if post_btn.is_visible():
        print("🚀 Clicking Post button with force=True...")
        post_btn.click(force=True)
    else:
        print("🚀 Pressing Ctrl+Enter...")
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")

    print("⏳ Đang chờ modal xuất bản đóng (tối đa 40s)...")
    modal_closed = False
    for i in range(20):
        modal = page.locator("div[role='dialog']:has([aria-label='Post']), div[role='dialog']:has([aria-label='Đăng'])")
        if modal.count() == 0 or not modal.first.is_visible():
            print(f"✅ Modal đã đóng sau {(i+1)*2}s!")
            modal_closed = True
            break
        page.wait_for_timeout(2000)

    page.wait_for_timeout(10000)
    page.screenshot(path="FacebookAutoPoster/step_after_post.png")

    # Điều hướng về profile để bình luận link YouTube
    print(f"🔄 Mở profile {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(6000)
    page.mouse.wheel(0, 450)
    page.wait_for_timeout(2000)

    # Chụp ảnh profile
    page.screenshot(path="FacebookAutoPoster/profile_after_day2.png")
    print("📸 Saved: profile_after_day2.png")

    # Tìm ô comment trên bài mới nhất
    leave_comment = 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_comment.is_visible():
        try:
            leave_comment.click(force=True)
            page.wait_for_timeout(2000)
        except Exception:
            pass

    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():
        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(400)
        print("✍️ 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 link YouTube thành công!")

        page.screenshot(path="FacebookAutoPoster/day2_final_published.png")
        print("📸 Saved: day2_final_published.png")
    else:
        print("⚠️ Không định vị được ô comment.")
