import sys
import time
from playwright.sync_api import sync_playwright

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

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!"
)

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

    # Target the "Write a comment..." box visible on screen right now
    comment_box = page.locator("div[role='textbox'][contenteditable='true'][aria-label*='Write a comment'], div[role='textbox'][contenteditable='true'][aria-label*='comment'], div[role='textbox'][contenteditable='true']").first
    print("Comment box visible:", comment_box.is_visible())

    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)
        print("Submitting comment via Enter key...")
        page.keyboard.press("Enter")
        time.sleep(4)

        ss_path = "FacebookAutoPoster/ep2_short1_final_verified_live.png"
        page.screenshot(path=ss_path)
        print(f"🎉 COMMENT SUCCESSFUL! Saved screenshot to: {ss_path}")
    else:
        print("⚠️ Comment box not found directly, trying to click comment button first...")
        c_btn = page.locator("div[role='button'][aria-label*='Leave a comment'], div[role='button'][aria-label*='Comment']").first
        if c_btn.is_visible():
            c_btn.click(force=True)
            time.sleep(1)
            comment_box = page.locator("div[role='textbox'][contenteditable='true']").first
            if comment_box.is_visible():
                comment_box.click(force=True)
                page.keyboard.insert_text(YOUTUBE_COMMENT)
                time.sleep(1)
                page.keyboard.press("Enter")
                time.sleep(4)
                page.screenshot(path="FacebookAutoPoster/ep2_short1_final_verified_live.png")
                print("Comment posted via button click!")
