import os
import sys
import time
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/ep1_short_2.mp4").resolve())
CAPTION_FILE = "FacebookAutoPoster/post_content_ep1_short2.txt"
YOUTUBE_COMMENT = (
    "🎬 Watch the complete Episode 1 in 4K UHD on YouTube:\n"
    "👉 https://youtu.be/DT202N1I4-A\n\n"
    "Subscribe to @thehistoricalvault-z9 for weekly 4K historical releases!"
)

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 2 sạch & chuẩn xác...")
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()

    # Bước 1: Mở trang chủ Facebook sạch
    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)

    # Bước 2: Kích hoạt nút 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:
        # Mở What's on your mind trước
        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/day2_step2_video_loaded.png")

    # Bước 3: Xử lý 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)

    # Bước 4: Nhập Caption
    print("4️⃣ 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)
        # Bấm Escape để đóng gợi ý hashtag nếu đang hiện ra
        page.keyboard.press("Escape")
        page.wait_for_timeout(1000)
        print("✅ Đã nhập caption hoàn chỉnh!")

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

    # Bước 5: Bấm nút Post và chờ xuất bản
    print("5️⃣ Bấm nút Post...")
    post_btn = page.locator("div[role='dialog'] div[aria-label='Post'], div[role='dialog'] div[role='button']:has-text('Post')").last
    if not post_btn.is_visible():
        post_btn = page.locator("div[role='dialog'] [aria-label='Post'], div[role='dialog'] [aria-label='Đăng']").first

    if post_btn.is_visible():
        print("Clicking Post button with 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ờ Facebook xử lý và xuất bản video...")
    for i in range(25):
        modal = page.locator("div[role='dialog']:has([aria-label='Đăng']), div[role='dialog']:has([aria-label='Post'])")
        if modal.count() == 0 or not modal.first.is_visible():
            print(f"✅ Modal tạo bài viết đã đóng sau {(i+1)*2}s!")
            break
        page.wait_for_timeout(2000)

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

    # Bước 6: Điều hướng trang cá nhân và tự động ghim bình luận YouTube link
    print(f"6️⃣ Mở trang cá nhân {PROFILE_URL} để tự động bình luận link YouTube...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(6000)

    # Cuộn nhẹ
    page.mouse.wheel(0, 450)
    page.wait_for_timeout(2000)

    # Tìm bài viết đầu tiên trên feed
    first_post = page.locator("div[role='feed'] > div, div[role='article']").first
    print("First post text preview:", first_post.inner_text()[:150] if first_post.count() > 0 else "None")

    # Bấm nút Leave a comment
    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 thành công link YouTube!")

        final_ss = "FacebookAutoPoster/day2_final_success.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 định vị được ô comment.")
