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_1.mp4").resolve())
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 quy trình xuất bản Day 3 Short 1 (Episode 2: 50,000 Invaders)...")

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

    # 1. Điều hướng về Facebook Home
    print("1️⃣ Mở https://www.facebook.com/...")
    page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(3000)
    page.keyboard.press("Escape")
    page.wait_for_timeout(1000)

    # 2. Chọn file qua Photo/video trên Feed chính
    print("2️⃣ Tìm và kích hoạt nút Photo/video để chọn file...")
    feed_photo_btn = page.locator("div[role='main'] [aria-label*='Photo/video'], div[role='main'] [aria-label*='Ảnh/video'], [aria-label*='Photo/video']").first
    
    file_uploaded = False
    if feed_photo_btn.is_visible():
        try:
            print("Kích hoạt file chooser từ feed_photo_btn...")
            with page.expect_file_chooser(timeout=7000) as fc_info:
                feed_photo_btn.click()
            fc = fc_info.value
            fc.set_files(VIDEO_PATH)
            file_uploaded = True
            print("✅ Đã chọn file video thành công qua feed_photo_btn!")
        except Exception as e:
            print(f"Không mở file chooser qua feed button: {e}")

    if not file_uploaded:
        print("Mở modal 'What's on your mind'...")
        wom = page.locator("[aria-label*=\"What's on your mind\"], [aria-label*=\"Bạn đang nghĩ gì\"]").first
        if wom.is_visible():
            wom.click()
            page.wait_for_timeout(2000)
        
        dialog_photo = page.locator("div[role='dialog'] [aria-label*='Photo/video'], div[role='dialog'] [aria-label*='Ảnh/video']").first
        if dialog_photo.is_visible():
            with page.expect_file_chooser(timeout=7000) as fc_info:
                dialog_photo.click()
            fc = fc_info.value
            fc.set_files(VIDEO_PATH)
            file_uploaded = True
            print("✅ Đã chọn file video thành công qua dialog Photo/video button!")

    print("⏳ Đang chờ video nạp vào modal (12s)...")
    page.wait_for_timeout(12000)
    page.screenshot(path="FacebookAutoPoster/ep2_step2_video_loaded.png")

    # 3. Kiểm tra popup "Review audience" nếu có
    print("3️⃣ Kiểm tra popup 'Review audience'...")
    continue_btn = page.locator("span:has-text('Continue'), div[role='dialog'] div[role='button']:has-text('Continue'), div[role='button']:has-text('Tiếp tục'), div[aria-label='Continue']").first
    if continue_btn.is_visible():
        print("🎯 Bấm Continue...")
        continue_btn.click(force=True)
        page.wait_for_timeout(2000)

    # 4. Kiểm tra nút chọn Audience -> Chọn Public nếu đang là Friends
    print("4️⃣ Kiểm tra audience selector...")
    aud_btn = page.locator("div[role='dialog'] div[aria-haspopup='dialog']:has-text('Friends'), div[role='dialog'] div[role='button']:has-text('Friends')").first
    if aud_btn.is_visible():
        try:
            print("Đổi audience sang Public...")
            aud_btn.click(force=True)
            page.wait_for_timeout(1500)
            pub_option = page.locator("div[role='dialog'] div[role='radio']:has-text('Public'), div[role='dialog'] span:has-text('Public')").first
            if pub_option.is_visible():
                pub_option.click(force=True)
                page.wait_for_timeout(1000)
                done_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Done'), div[role='dialog'] div[role='button']:has-text('Save')").first
                if done_btn.is_visible():
                    done_btn.click(force=True)
                    page.wait_for_timeout(1000)
                print("✅ Đã chọn audience: Public!")
        except Exception as e:
            print(f"Audience change note: {e}")

    # 5. Nhập Caption
    print("5️⃣ Nhập caption tiếng Anh...")
    textbox = page.locator("div[role='dialog'] div[role='textbox'][contenteditable='true']").first
    if not textbox.is_visible():
        textbox = page.locator("div[role='textbox'][contenteditable='true']").last

    if textbox.is_visible():
        try:
            textbox.focus()
            page.wait_for_timeout(300)
            textbox.click(force=True)
        except Exception:
            textbox.focus()
        page.wait_for_timeout(400)
        page.keyboard.press("Control+a")
        page.keyboard.press("Backspace")
        page.wait_for_timeout(300)
        page.keyboard.insert_text(caption)
        page.wait_for_timeout(1000)
        page.keyboard.press("Escape")
        page.wait_for_timeout(1000)
        print("✅ Đã nhập caption hoàn chỉnh!")

    page.screenshot(path="FacebookAutoPoster/ep2_step5_caption_ready.png")
    print("📸 Đã chụp: ep2_step5_caption_ready.png")

    # 6. Bấm nút Post
    print("6️⃣ Bấm nút Post...")
    post_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Post'), div[role='dialog'] div[aria-label='Post']").last
    if not post_btn.is_visible():
        post_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Đăng'), div[role='dialog'] div[aria-label='Đăng']").first

    print("Post button text:", post_btn.inner_text() if post_btn.count() > 0 else "None")
    if post_btn.is_visible():
        print("🚀 Bấm Post button (force=True)...")
        post_btn.click(force=True)
    else:
        print("🚀 Bấm Ctrl+Enter...")
        page.keyboard.down("Control")
        page.keyboard.press("Enter")
        page.keyboard.up("Control")

    print("⏳ Đang chờ modal tạo bài viết hoàn tất xuất bản...")
    modal_closed = False
    for i in range(30):
        # Kiểm tra xem modal Create post còn hiển thị không
        active_modal = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')")
        if active_modal.count() == 0 or not active_modal.first.is_visible():
            print(f"🎉 Modal tạo bài viết đã đóng hoàn tất sau {(i+1)*2} giây!")
            modal_closed = True
            break
        page.wait_for_timeout(2000)

    if not modal_closed:
        print("⚠️ Modal chưa tự đóng sau 60s, thử click nút Post lại một lần nữa...")
        post_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Post')").last
        if post_btn.is_visible():
            post_btn.click(force=True)
            page.wait_for_timeout(10000)

    page.screenshot(path="FacebookAutoPoster/ep2_step6_after_post.png")
    print("📸 Đã chụp: ep2_step6_after_post.png")

    # 7. Chờ Facebook transcode video (30s)
    print("⏳ Đang chờ Facebook mã hóa video lên hệ thống (30s)...")
    page.wait_for_timeout(30000)

    # 8. Mở Profile cá nhân để kiểm tra và ghim bình luận YouTube link
    print(f"8️⃣ Mở trang cá nhân {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(6000)

    page.mouse.wheel(0, 400)
    page.wait_for_timeout(2000)

    page.screenshot(path="FacebookAutoPoster/ep2_step8_profile_scrolled.png")
    print("📸 Đã chụp: ep2_step8_profile_scrolled.png")

    # Tìm ô comment trên bài viết 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 cho Tập 2...")
        page.keyboard.insert_text(YOUTUBE_COMMENT)
        page.wait_for_timeout(1500)
        page.keyboard.press("Enter")
        page.wait_for_timeout(5000)
        print("✅ Đã ghim thành công bình luận link YouTube!")

        final_ss = "FacebookAutoPoster/ep2_short1_verified_live.png"
        page.screenshot(path=final_ss)
        print(f"🎉 Bằng chứng xác thực lưu tại: {final_ss}")
    else:
        print("⚠️ Chưa thấy ô comment, chụp ảnh kiểm tra.")
        page.screenshot(path="FacebookAutoPoster/ep2_comment_failed_debug.png")

# 9. 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}")
