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 cho Short 1 Tập 2 và bấm Post...")
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/ep2_short1_caption_ready.png")
    print("📸 Saved: ep2_short1_caption_ready.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)...")
    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!")
            break
        page.wait_for_timeout(2000)

    # Chờ video transcode 25s
    print("⏳ Đang chờ Facebook xử lý video và xuất hiện trên Timeline (25s)...")
    page.wait_for_timeout(25000)

    # Mở profile cá nhân để ghim bình luận
    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)

    # 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 4K...")
        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!")

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

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