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"
CAPTION_FILE = "FacebookAutoPoster/post_content_ep2_short1.txt"
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"

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ào modal đang mở và nhấn Post...")

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

    # 1. Tìm ô textbox trong dialog
    dialog = page.locator("div[role='dialog']").first
    print("Dialog is visible:", dialog.is_visible())

    textbox = dialog.locator("div[role='textbox'][contenteditable='true']").first
    print("Textbox visible:", textbox.is_visible())
    if textbox.is_visible():
        textbox.click(force=True)
        time.sleep(0.5)
        # Type caption
        print("Gõ caption...")
        page.keyboard.insert_text(caption)
        time.sleep(1)
        # Escape any hashtag suggestion dropdown
        page.keyboard.press("Escape")
        time.sleep(1)
        print("✅ Đã gõ caption xong!")

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

    # 2. Tìm nút Post
    post_btn = dialog.locator("div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    
    if post_btn.is_visible():
        print("🚀 Bấm nút Post...")
        post_btn.click(force=True)
    else:
        print("🚀 Bấm Ctrl+Enter...")
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")

    # 3. Chờ modal đóng hoàn toàn
    print("⏳ Đang theo dõi modal đóng...")
    modal_closed = False
    for i in range(40):
        # Kiểm tra nếu dialog chứa "Create post" đã biến mất
        create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')")
        if create_dialog.count() == 0 or not create_dialog.first.is_visible():
            print(f"🎉 Modal đã đóng thành công sau {(i+1)*2} giây!")
            modal_closed = True
            break
        time.sleep(2)

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

    # 4. Chờ 25s cho Facebook xử lý video
    print("⏳ Đang chờ 25 giây cho hệ thống Facebook đồng bộ video...")
    time.sleep(25)

    # 5. Mở trang cá nhân để kiểm tra và bình luận link YouTube
    print(f"🔄 Mở trang cá nhân: {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(5)
    page.mouse.wheel(0, 450)
    time.sleep(2)

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

    # 6. Tìm ô Leave a comment của bài viết đầu tiên
    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)
            time.sleep(2)
        except Exception as e:
            print("Leave comment click:", e)

    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():
        comment_box.click(force=True)
        time.sleep(0.5)
        print("✍️ Gõ bình luận link YouTube 4K...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        time.sleep(1.5)
        page.keyboard.press("Enter")
        time.sleep(5)
        print("🎉 Đã gửi bình luận link YouTube thành công!")

        page.screenshot(path="FacebookAutoPoster/ep2_short1_live_verified.png")
        print("📸 Saved: FacebookAutoPoster/ep2_short1_live_verified.png")
    else:
        print("⚠️ Chưa thấy ô comment trên bài mới nhất.")

# 7. Cập nhật 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!")
except Exception as e:
    print(f"Lỗi cập nhật lịch: {e}")
