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)

    post_text = """🚨 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 troops breached the Mekong Delta. With the royal Nguyen army scattered and Lord Nguyen Anh in exile, who could possibly stand against them?

🎬 Missed Episode 1? Catch up now before the 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"""

    # 1. Click into post input box
    print("[*] Focusing post text box...")
    editor = manager.page.locator("#contenteditable-root").first
    if editor.is_visible(timeout=5000):
        editor.click()
        time.sleep(1)

        # 2. Upload image first by clicking "Hình ảnh" button or setting input
        img_path = str(Path("content/thumbnails_4k/ep2_thumb_4k.jpg").resolve())
        print(f"[*] Attaching teaser artwork: {img_path}")
        
        # Click image button to open file selector or activate dropzone
        img_btn = manager.page.locator("#image-button, button:has-text('Hình ảnh')").first
        if img_btn.is_visible():
            img_btn.click()
            time.sleep(2)

        file_input = manager.page.locator("input[type='file'][accept*='image']").first
        if file_input.count() > 0:
            file_input.set_input_files(img_path)
            print("  ✓ Image file input set.")
            time.sleep(5)

        # 3. Enter post text
        print("[*] Typing post content...")
        manager.page.evaluate("""
        (text) => {
            const root = document.querySelector('#contenteditable-root');
            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 }));
            }
        }
        """, post_text)
        time.sleep(2)

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

    # 4. Click Submit / Đăng
    print("[*] Submitting community post...")
    submit_btn = manager.page.locator("#submit-button button, ytd-button-renderer#submit-button button, button:has-text('Đăng')").first
    if submit_btn.is_visible(timeout=5000):
        is_disabled = submit_btn.is_disabled()
        print("Submit button disabled?:", 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(8)
        else:
            print("[-] Nút Đăng đang bị disabled.")

    manager.capture_status("downloads/community_post_published.png")
    print("Done!")

finally:
    manager.close()
