import sys
import time
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"
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!"
)

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

    print("Navigating to profile...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(5)
    page.mouse.wheel(0, 600)
    time.sleep(3)

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

    # Search for our post
    posts = page.locator("div[role='feed'] > div, div[role='article'], div[data-pagelet*='FeedUnit']").all()
    print(f"Total posts found: {len(posts)}")

    target_post = None
    for i, post in enumerate(posts[:6]):
        txt = post.inner_text().replace('\n', ' ')
        print(f"Post {i}: {txt[:100]}")
        if "EUROPEAN ARTILLERY" in txt or "deadly Siamese naval assault" in txt or "Portuguese-cast" in txt:
            target_post = post
            print(f"🎯 ĐÃ TÌM THẤY BÀI VIẾT SHORT 2 Ở VỊ TRÍ {i}!")
            break

    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("Clicking comment button...")
            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("Typing YouTube 4K link comment...")
            page.keyboard.insert_text(YOUTUBE_COMMENT)
            time.sleep(1.5)
            page.keyboard.press("Enter")
            print("🚀 Comment submitted!")
            time.sleep(5)

            page.screenshot(path="FacebookAutoPoster/video_short2_commented_live.png")
            print("Saved video_short2_commented_live.png!")
        else:
            print("Comment box not found.")
    else:
        print("Video still processing on Facebook transcoder...")
