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)

    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)

    # Trigger Polymer input change
    manager.page.keyboard.press("End")
    manager.page.keyboard.type(" ")
    time.sleep(0.3)
    manager.page.keyboard.press("Backspace")
    time.sleep(2)

    # Scroll down slightly so buttons are fully in view
    manager.page.mouse.wheel(0, 300)
    time.sleep(1)

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

    # 3. Click Submit via DOM & Playwright
    print("[*] Clicking [Đăng] button...")
    clicked = manager.page.evaluate("""
    () => {
        // Find submit button inside backstage post renderer or page
        const btn = document.querySelector('#submit-button button') || 
                    document.querySelector('ytd-button-renderer#submit-button button') ||
                    Array.from(document.querySelectorAll('button')).find(b => (b.innerText || '').trim() === 'Đăng');
        if (btn) {
            btn.click();
            return { success: true, text: btn.innerText };
        }
        return { success: false };
    }
    """)
    print("Click result:", clicked)
    time.sleep(6)

    manager.capture_status("downloads/community_post_success.png")
    print("All done!")

finally:
    manager.close()
