import sys, os, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from youtube_studio_manager import YouTubeStudioManager

manager = YouTubeStudioManager(mode='chrome_stealth')
manager.start(headless=False)

try:
    url = "https://www.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/posts"
    print(f"[*] Navigating to Community tab: {url}")
    manager.page.goto(url, wait_until="domcontentloaded", timeout=45000)
    time.sleep(6)

    # 1. Click placeholder
    box = manager.page.locator("#placeholder, yt-formatted-string:has-text('người hâm mộ'), #simplebox-placeholder, [id*='placeholder']").first
    if box.is_visible(timeout=5000):
        box.click()
        time.sleep(2)
        print("✓ Clicked placeholder.")

    # 2. Type full post text
    post_lines = [
        "🚨 TONIGHT AT 19:00 VN / 08:30 EST: EPISODE 2 PREMIERE! ⚔️🔥",
        "",
        "\"50,000 Invaders: The Siamese Fleet Invades the South\" drops in full 4K UHD!",
        "",
        "In 1785, an overwhelming armada of 300 Siamese warships and 50,000 elite soldiers breached the Mekong Delta. With the royal Nguyen navy scattered and Prince Nguyen Anh in exile, who could possibly stand against them?",
        "",
        "🎬 Missed Episode 1? Catch up now before tonight's premiere:",
        "👉 https://youtu.be/DT202N1I4-A",
        "",
        "🔔 Turn on notifications so you don't miss the battle! What do you think was the fatal tactical blunder of the invading armada? Let us know below! 👇",
        "",
        "#HistoryVault #UntoldBattles #NavalHistory #4K #Warfare #RachGam1785"
    ]

    full_text = "\n".join(post_lines)

    # Use evaluate execCommand to insert entire text cleanly with linebreaks
    manager.page.evaluate("""
    (text) => {
        const root = document.querySelector('#contenteditable-root') || document.querySelector('[contenteditable="true"]');
        if (root) {
            root.focus();
            document.execCommand('selectAll', false, null);
            document.execCommand('insertText', false, text);
            root.dispatchEvent(new Event('input', { bubbles: true }));
            root.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
    """, full_text)
    time.sleep(2)

    # Type an extra space and backspace via keyboard to ensure Polymer triggers button enable
    manager.page.keyboard.press("End")
    manager.page.keyboard.type(" ")
    time.sleep(0.3)
    manager.page.keyboard.press("Backspace")
    time.sleep(1)

    manager.capture_status("downloads/community_ready_to_publish.png")

    # 3. Check submit button
    submit_btn = manager.page.locator("ytd-button-renderer#submit-button button, button:has-text('Đăng')").first
    print("Submit button visible?:", submit_btn.is_visible(timeout=5000))
    if submit_btn.is_visible():
        is_disabled = submit_btn.is_disabled()
        print(f"Submit button disabled state: {is_disabled}")
        if not is_disabled:
            submit_btn.click()
            print("🎉 BẤM NÚT [ĐĂNG] BÀI VIẾT THÀNH CÔNG!")
            time.sleep(6)
        else:
            print("[-] Nút Đăng đang disabled.")

    manager.capture_status("downloads/community_post_live.png")
    print("Completed!")

finally:
    manager.close()
