import os
import sys
import time
import json
from pathlib import Path
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"
VIDEO_PATH = str(Path("content/shorts/ep2_short_2.mp4").resolve())
CAPTION = (
    "💥 EUROPEAN ARTILLERY ON ASIAN RIVERS: The deadly Siamese naval assault (1785)\n\n"
    "Portuguese-cast cannons tear through river defenses as the coalition armada pushes deep into Vietnamese territory...\n\n"
    "👉 Experience the full naval war in 4K UHD! Link pinned in comments.\n\n"
    "#AncientWarfare #NavalTactics #MilitaryHistory #Artillery #HistoricalDocumentary"
)
YOUTUBE_COMMENT = (
    "🎬 Experience the full naval warfare in 4K UHD:\n"
    "👉 https://youtu.be/FKPhXdwFbII\n\n"
    "Subscribe to @thehistoricalvault-z9 for weekly 4K historical releases!"
)
SCHEDULE_FILE = "content/MARKETING_SCHEDULE.json"

print(f"Connecting to browser on port 9224...")
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    # Close any open dialogs or draft prompts
    draft_close = page.locator("div[role='dialog']:has-text('Save this post as a draft') div[aria-label='Close'], div[role='dialog']:has-text('Lưu bài viết này làm bản nháp') div[aria-label='Đóng']").first
    if draft_close.is_visible():
        print("Closing draft prompt...")
        draft_close.click(force=True)
        time.sleep(1)

    page.keyboard.press("Escape")
    time.sleep(1)

    print(f"Navigating to {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.keyboard.press("Escape")
    time.sleep(1)

    # 1. Open Create post dialog
    print("Mở hộp thoại tạo bài viết trên trang cá nhân...")
    wom = page.locator("div[role='main'] div[role='button']:has-text(\"What's on your mind\"), div[role='button']:has-text(\"Bạn đang nghĩ gì\")").first
    if wom.is_visible():
        wom.click(force=True)
        time.sleep(2)

    # 2. Locate dialog
    create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
    print("Create post dialog visible:", create_dialog.is_visible())

    # 3. Upload Video
    photo_btn = create_dialog.locator("div[role='button'][aria-label*='Photo/video'], div[role='button'][aria-label*='Ảnh/video']").first
    if photo_btn.is_visible():
        try:
            with page.expect_file_chooser(timeout=7000) as fc_info:
                photo_btn.click(force=True)
            fc = fc_info.value
            fc.set_files(VIDEO_PATH)
            print(f"✅ Đã nạp file video: {VIDEO_PATH}! Chờ 10s Facebook xử lý upload...")
            time.sleep(10)
        except Exception as e:
            print("File chooser exception, fallback to input[type=file]:", e)
            file_input = page.locator("input[type='file']").first
            if file_input.count() > 0:
                file_input.set_input_files(VIDEO_PATH)
                time.sleep(10)

    # 4. Insert Caption
    textbox = create_dialog.locator("div[role='textbox'][contenteditable='true']").first
    if textbox.is_visible():
        textbox.click(force=True)
        time.sleep(0.5)
        page.keyboard.insert_text(CAPTION)
        time.sleep(1.5)
        page.keyboard.press("Escape")
        time.sleep(1)
        print("✅ Đã nhập caption xong!")

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

    # 5. Click Post
    post_btn = create_dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    is_disabled = post_btn.get_attribute("aria-disabled")
    print(f"Post button aria-disabled: {is_disabled}")

    if post_btn.is_visible() and is_disabled != "true":
        print("🚀🚀🚀 BẤM NÚT POST DAY 3 SHORT 2! 🚀🚀🚀")
        post_btn.click(force=True)
        time.sleep(15)
        page.screenshot(path="FacebookAutoPoster/ep2_short2_post_clicked.png")
        print("Saved ep2_short2_post_clicked.png")
    else:
        print("⚠️ Nút Post bị disabled hoặc không tìm thấy!")

    # 6. Chờ transcode 30 giây rồi ghim comment YouTube 4K link
    print("⏳ Chờ 30 giây để Facebook xử lý video và đưa lên timeline...")
    time.sleep(30)

    print(f"🔄 Tải lại trang cá nhân: {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(5)
    page.mouse.wheel(0, 500)
    time.sleep(3)

    # Tìm bài viết Short 2
    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', ' ')
        if "EUROPEAN ARTILLERY" in txt or "deadly Siamese naval assault" in txt:
            target_post = post
            print(f"🎯 ĐÃ TÌM THẤY BÀI VIẾT SHORT 2 Ở VỊ TRÍ {i}!")
            break

    if target_post is None and posts:
        target_post = posts[0]
        print("Sử dụng bài viết trên cùng.")

    if target_post:
        target_post.scroll_into_view_if_needed()
        time.sleep(1)

        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)

        comment_box = target_post.locator("div[role='textbox'][contenteditable='true']").first
        if not comment_box.is_visible():
            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_short2_final_verified_live.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.")

# 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_2.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 2 thành published_automated trong MARKETING_SCHEDULE.json!")
except Exception as e:
    print(f"Lỗi cập nhật lịch: {e}")
