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"

def ensure_chrome():
    import urllib.request
    import subprocess
    try:
        with urllib.request.urlopen("http://127.0.0.1:9224/json", timeout=2) as resp:
            if resp.status == 200:
                return True
    except Exception:
        pass

    print("[Tự động hồi phục] Khởi động Chrome Native cổng 9224...")
    ps1_path = r"C:\Projects\Historical\FacebookAutoPoster\open_stealth_chrome.ps1"
    subprocess.Popen(["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", ps1_path])
    for i in range(15):
        time.sleep(1)
        try:
            with urllib.request.urlopen("http://127.0.0.1:9224/json", timeout=2) as resp:
                if resp.status == 200:
                    print("✅ Chrome Native đã sẵn sàng!")
                    return True
        except Exception:
            pass
    return False

def run_publish():
    ensure_chrome()
    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 xuất bản Short 1 Tập 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. Mở trang chủ Facebook sạch
        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. Mở hộp thoại tạo bài viết
        print("Mở hộp thoại tạo bài viết...")
        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)
        else:
            page.keyboard.press("p")
            page.wait_for_timeout(2000)

        # 3. Nạp video qua file chooser của nút Photo/video trong dialog
        print("Đính kèm video Short 1 Tập 2...")
        photo_btn = page.locator("div[role='dialog'] [aria-label*='Photo/video'], div[role='dialog'] [aria-label*='Ảnh/video'], [aria-label*='Photo/video']").first
        if photo_btn.is_visible():
            try:
                with page.expect_file_chooser(timeout=8000) as fc_info:
                    photo_btn.click()
                fc = fc_info.value
                fc.set_files(VIDEO_PATH)
                print("✅ Đã nạp file video qua file chooser!")
            except Exception as e:
                print(f"File chooser qua nút: {e}")
                file_inputs = page.locator("input[type='file']")
                if file_inputs.count() > 0:
                    file_inputs.first.set_input_files(VIDEO_PATH)
                    print("✅ Đã nạp file video qua file input!")

        print("Đang chờ video nạp vào modal (12s)...")
        page.wait_for_timeout(12000)

        # 4. Kiểm tra popup Review audience nếu có
        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 trên Review audience...")
            continue_btn.click(force=True)
            page.wait_for_timeout(2000)

        # 5. Nhập Caption tiếng Anh
        print("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)
            # Đóng dropdown gợi ý hashtag
            page.keyboard.press("Escape")
            page.wait_for_timeout(1000)
            print("✅ Đã nhập caption thành công!")

        # 6. Bấm nút Post
        print("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

        if post_btn.is_visible():
            post_btn.click(force=True)
            print("✅ Đã bấm nút Post!")
        else:
            page.keyboard.down("Control")
            page.keyboard.press("Enter")
            page.keyboard.up("Control")

        # Chờ modal đóng
        print("Chờ modal đóng (tối đa 40s)...")
        for _ 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("✅ Modal tạo bài viết đã đóng hoàn tất!")
                break
            page.wait_for_timeout(2000)

        # Chờ video transcode 20s
        print("Chờ Facebook xử lý video (20s)...")
        page.wait_for_timeout(20000)

        # 7. Mở profile cá nhân để ghim bình luận link YouTube 4K
        print(f"Mở trang cá nhân {PROFILE_URL}...")
        page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
        page.wait_for_timeout(5000)
        page.mouse.wheel(0, 450)
        page.wait_for_timeout(2000)

        # Định vị ô bình luận trên bài viết vừa xuất hiện
        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():
            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 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 4K vào bài đăng!")

            final_ss = "FacebookAutoPoster/ep2_short1_final_verified.png"
            page.screenshot(path=final_ss)
            print(f"📸 Đã lưu ảnh xác thực tại: {final_ss}")
        else:
            print("⚠️ Không định vị được ô nhập bình luận.")

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

if __name__ == "__main__":
    run_publish()
