import sys
import time
import json
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 full Episode 2 battle documentary in 4K UHD on YouTube:\n"
    "👉 https://youtu.be/FKPhXdwFbII\n\n"
    "Subscribe to @thehistoricalvault-z9 for weekly 4K historical releases!"
)
SCHEDULE_FILE = "content/MARKETING_SCHEDULE.json"

print("⏳ Chờ 30 giây để Facebook hoàn tất mã hóa video...")
time.sleep(30)

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

    # Đóng mọi modal còn lại
    page.keyboard.press("Escape")
    time.sleep(1)

    print(f"🔄 Mở trang cá nhân: {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(5)

    # Cuộn xuống khu vực bài viết
    page.mouse.wheel(0, 500)
    time.sleep(3)

    page.screenshot(path="FacebookAutoPoster/profile_after_ep2_transcode.png")
    print("Saved profile_after_ep2_transcode.png")

    # Kiểm tra xem bài mới nhất có chứa "300 SIAMESE WARSHIPS" hay không
    posts = page.locator("div[role='feed'] > div, div[role='article'], div[data-pagelet*='FeedUnit']").all()
    print(f"Tìm thấy {len(posts)} bài viết trên feed.")

    target_post = None
    for i, post in enumerate(posts[:5]):
        txt = post.inner_text().replace('\n', ' ')
        print(f"Post {i}: {txt[:100]}")
        if "300 SIAMESE WARSHIPS INVADE THE MEKONG DELTA" in txt or "Forgotten Battles Ep 2" in txt:
            target_post = post
            print(f"🎯 ĐÃ TÌM THẤY BÀI VIẾT EPISODE 2 Ở VỊ TRÍ {i}!")
            break

    if target_post is None and posts:
        # Nếu chưa thấy ngay, có thể là bài đầu tiên
        target_post = posts[0]
        print("Sử dụng bài viết đầu tiên trên Timeline.")

    if target_post:
        # Cuộn vào bài viết
        target_post.scroll_into_view_if_needed()
        time.sleep(1)

        # Tìm nút Comment trên bài viết này
        comment_btn = target_post.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 comment_btn.is_visible():
            print("Bấm nút Comment trên bài viết...")
            comment_btn.click(force=True)
            time.sleep(2)

        # Tìm ô comment
        comment_box = target_post.locator("div[role='textbox'][contenteditable='true']").first
        if not comment_box.is_visible():
            # Thử tìm trên toàn page
            comment_box = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a comment'], div[role='textbox'][contenteditable='true'][aria-label*='comment']").first

        if comment_box.is_visible():
            comment_box.click(force=True)
            time.sleep(0.5)
            print("✍️ Đang gõ bình luận link YouTube 4K...")
            page.keyboard.insert_text(YOUTUBE_COMMENT)
            time.sleep(1.5)
            page.keyboard.press("Enter")
            print("🚀 Đã bấm Enter gửi bình luận! Chờ 5s...")
            time.sleep(5)

            final_ss = "FacebookAutoPoster/ep2_short1_final_live_verified.png"
            page.screenshot(path=final_ss)
            print(f"🎉 Bằng chứng xác thực cuối cùng đã lưu tại: {final_ss}")
        else:
            print("⚠️ Không tìm thấy ô comment.")
            page.screenshot(path="FacebookAutoPoster/ep2_comment_box_not_found.png")

# Cập nhật lịch trình MARKETING_SCHEDULE.json
try:
    with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
        sched = json.load(f)
    for item in sched.get("schedule", []):
        if item.get("day") == 3 and item.get("video") == "content/shorts/ep2_short_1.mp4":
            item["status"] = "published_automated"
            item["published_at"] = time.strftime("%Y-%m-%d %H:%M PST")
            break
    with open(SCHEDULE_FILE, "w", encoding="utf-8") as f:
        json.dump(sched, f, ensure_ascii=False, indent=2)
    print("✅ Đã cập nhật trạng thái Day 3 Short 1 thành published_automated trong MARKETING_SCHEDULE.json!")
except Exception as e:
    print(f"Lỗi cập nhật lịch: {e}")
