import os
import sys
import time
import argparse
from pathlib import Path
from playwright.sync_api import sync_playwright

# Hỗ trợ bảng mã UTF-8 trên Windows console
if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass

CDP_URL = "http://127.0.0.1:9224"
PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"

def post_comment_on_latest_post(page, comment_text: str):
    """
    Sau khi đăng bài xong, điều hướng về profile cá nhân và tự động bình luận link YouTube vào bài đăng mới nhất.
    """
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ⏳ Đang chờ hệ thống Facebook xử lý và hiển thị bài viết...")
    page.wait_for_timeout(10000)

    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🔄 Đang mở trang cá nhân để định vị bài đăng mới nhất...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=60000)
    page.wait_for_timeout(5000)

    # Cuộn nhẹ xuống khu vực bài viết
    page.mouse.wheel(0, 500)
    page.wait_for_timeout(2000)

    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🔍 Đang tìm nút mở bình luận trên bài viết vừa đăng...")
    leave_comment_btn = page.locator(
        'div[role="button"][aria-label*="Leave a comment"], '
        'div[role="button"][aria-label*="Bình luận"], '
        'div[role="button"][aria-label*="Comment"]'
    ).first

    if leave_comment_btn.is_visible():
        leave_comment_btn.click()
        page.wait_for_timeout(2000)

    # Tìm ô nhập bình luận
    comment_box = page.locator(
        'div[role="textbox"][contenteditable="true"][aria-label*="Write a comment"], '
        'div[role="textbox"][contenteditable="true"][aria-label*="Viết bình luận"], '
        'div[role="textbox"][contenteditable="true"][aria-label*="comment"], '
        'div[role="textbox"][contenteditable="true"][aria-label*="bình luận"]'
    ).first

    if not comment_box.is_visible():
        # Fallback vào textbox đang focus hoặc cuối cùng
        comment_box = page.locator('div[role="textbox"][contenteditable="true"]').last

    if comment_box.is_visible():
        comment_box.click()
        page.wait_for_timeout(500)
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ✍️ Đang gõ bình luận link YouTube...")
        page.keyboard.insert_text(comment_text)
        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 vào bài đăng!")

        # Chụp ảnh xác thực bài đăng kèm bình luận
        ss_path = "FacebookAutoPoster/post_and_comment_verified.png"
        page.screenshot(path=ss_path)
        print(f"📸 Đã chụp ảnh xác thực tại: {ss_path}")
        return True
    else:
        print("⚠️ Không định vị được ô nhập bình luận trên bài viết mới nhất.")
        ss_path = "FacebookAutoPoster/comment_failed.png"
        page.screenshot(path=ss_path)
        return False

def ensure_chrome_running():
    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] Chrome cổng 9224 chưa chạy, đang khởi động Chrome Native...")
    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(f"✅ Chrome Native cổng 9224 đã sẵn sàng sau {i+1}s!")
                    return True
        except Exception:
            pass
    return False

def post_content_via_cdp(content: str, video_path: str = None, comment_text: str = None):
    ensure_chrome_running()
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Đang kết nối vào Google Chrome Native qua cổng CDP 9224...")
    with sync_playwright() as p:
        try:
            browser = p.chromium.connect_over_cdp(CDP_URL)
        except Exception as e:
            print(f"❌ Không thể kết nối tới Chrome cổng 9224! ({e})")
            print("👉 Vui lòng kiểm tra Chrome Native đang chạy với --remote-debugging-port=9224.")
            return False

        context = browser.contexts[0]
        # Lấy tab Facebook hiện tại hoặc mở tab mới
        page = None
        for p_item in context.pages:
            if "facebook.com" in p_item.url:
                page = p_item
                break

        if not page:
            page = context.new_page()

        page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=60000)
        page.wait_for_timeout(3000)
        page.bring_to_front()
        print(f"✅ Đã kết nối tab Facebook: {page.url}")

        # Kiểm tra đăng nhập
        if "login" in page.url or page.locator('input[name="email"]').is_visible():
            print("⚠️ CẢNH BÁO: Bạn chưa đăng nhập Facebook trên cửa sổ Chrome thật!")
            return False

        try:
            print("Đang mở form tạo bài viết...")
            page.keyboard.press("Escape")
            page.wait_for_timeout(1000)
            page.keyboard.press("p")
            page.wait_for_timeout(3000)

            # Fallback nếu phím tắt p không mở được modal
            composer_modal = page.locator("div[role='dialog']:has([aria-label='Đăng']), div[role='dialog']:has([aria-label='Post'])")
            if composer_modal.count() == 0 or not composer_modal.first.is_visible():
                whats_on_mind = page.locator("[aria-label*=\"What's on your mind\"], [aria-label*=\"Bạn đang nghĩ gì\"]").first
                if whats_on_mind.is_visible():
                    whats_on_mind.click()
                    page.wait_for_timeout(3000)

            # Nếu có video đính kèm (Shorts/Reels)
            if video_path and os.path.exists(video_path):
                v_file = str(Path(video_path).resolve())
                print(f"Đang đính kèm video Shorts: {v_file}...")

                file_attached = False
                photo_btn = page.locator("div[role='dialog'] [aria-label*='Photo/video'], div[role='dialog'] [aria-label*='Ảnh/video'], [aria-label*='Photo/video'], [aria-label*='Ảnh/video']").first
                if photo_btn.is_visible():
                    try:
                        print("Kích hoạt file chooser qua nút Photo/video...")
                        with page.expect_file_chooser(timeout=8000) as fc_info:
                            photo_btn.click()
                        file_chooser = fc_info.value
                        file_chooser.set_files(v_file)
                        file_attached = True
                        print("✅ Đã nạp file video thành công qua file chooser!")
                    except Exception as e:
                        print(f"File chooser qua nút không kích hoạt: {e}")

                if not file_attached:
                    file_inputs = page.locator("input[type='file']")
                    if file_inputs.count() > 0:
                        try:
                            file_inputs.first.set_input_files(v_file, timeout=5000)
                            file_attached = True
                            print("✅ Đã nạp file video thành công qua input[type='file']")
                        except Exception as e:
                            print(f"Lỗi nạp file trực tiếp: {e}")

                print("Đang chờ tải video lên trình duyệt (12s)...")
                page.wait_for_timeout(12000)

            # Điền caption tiếng Anh
            print("Đang gõ caption bài đăng...")
            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():
                textbox.click()
                page.wait_for_timeout(400)
                # Xóa bất kỳ ký tự thừa nào (như phím tắt p)
                page.keyboard.press("Control+a")
                page.keyboard.press("Backspace")
                page.wait_for_timeout(300)
                page.keyboard.insert_text(content)
                page.wait_for_timeout(2000)

            print("Đang xuất bản bài đăng...")
            page.wait_for_timeout(3000)
            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(timeout=10000)
            else:
                page.keyboard.down("Control")
                page.keyboard.press("Enter")
                page.keyboard.up("Control")

            print("✅ Đã phát lệnh Đăng thành công trên Google Chrome Native!")
            
            # Chờ modal xuất bản đóng lại
            for _ in range(20):
                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():
                    break
                page.wait_for_timeout(2000)

            page.wait_for_timeout(5000)

            # Nếu có yêu cầu tự động bình luận link YouTube
            if comment_text:
                post_comment_on_latest_post(page, comment_text)

            return True

        except Exception as e:
            print(f"❌ Lỗi tương tác: {e}")
            return False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Facebook Native Chrome CDP Poster with Auto-Comment")
    parser.add_argument("content_file", help="Path to text file containing caption")
    parser.add_argument("video_path", nargs="?", default=None, help="Path to video file")
    parser.add_argument("--comment", default=None, help="Custom comment text to post on the published post")
    parser.add_argument("--youtube-url", default=None, help="YouTube URL to format into standard first comment")

    args = parser.parse_args()

    with open(args.content_file, "r", encoding="utf-8") as f:
        caption = f.read()

    comment = args.comment
    if not comment and args.youtube_url:
        comment = f"🎬 Watch the full documentary in 4K UHD on YouTube:\n{args.youtube_url}"

    post_content_via_cdp(caption, args.video_path, comment)
