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:
    edit_url = "https://studio.youtube.com/video/MtB7VLHfcDk/edit"
    print(f"[*] Navigating to {edit_url}...")
    manager.page.goto(edit_url, wait_until="domcontentloaded", timeout=45000)
    time.sleep(5)

    # 1. Update Title cleanly
    new_title = "Zero Warships. Exiled Prince. How Did He Survive? ⚔️ #Shorts"
    print(f"[*] Updating Title to: {new_title}")
    
    manager.page.evaluate("""
    (val) => {
        const titleEl = document.querySelector('#title-textarea #textbox, #textbox[aria-label*="tiêu đề"], #textbox[aria-label*="title"]');
        if (titleEl) {
            titleEl.focus();
            titleEl.innerText = val;
            titleEl.dispatchEvent(new Event('input', { bubbles: true }));
            titleEl.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
    """, new_title)
    time.sleep(1)

    # Also type one backspace and character to trigger Polymer dirty check
    title_box = manager.page.locator("#title-textarea #textbox, #textbox[aria-label*='tiêu đề'], #textbox[aria-label*='title']").first
    if title_box.is_visible():
        title_box.click()
        manager.page.keyboard.press("End")
        manager.page.keyboard.type(" ")
        time.sleep(0.3)
        manager.page.keyboard.press("Backspace")
        time.sleep(0.5)

    # 2. Update Description
    new_desc = """In 1785, Prince Nguyen Anh lost everything to the unstoppable peasant army of Tay Son. Exiled on a remote island with zero warships, he forged a desperate alliance that ignited the bloodiest naval war in Southeast Asian history.

🎬 Watch the Full 36-Minute 4K Movie:
👉 https://youtu.be/c8Akru2j7ok

⚔️ Watch Episode 1 (4K UHD):
👉 https://youtu.be/DT202N1I4-A

#Shorts #History #Documentary #WarHistory #TaySon #NavalBattle #4K #HistoryVault"""

    print("[*] Updating Description...")
    manager.page.evaluate("""
    (text) => {
        const descEl = document.querySelector('#description-textarea #textbox, #textbox[aria-label*="mô tả"], #textbox[aria-label*="description"]');
        if (descEl) {
            descEl.focus();
            descEl.innerText = text;
            descEl.dispatchEvent(new Event('input', { bubbles: true }));
            descEl.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
    """, new_desc)
    time.sleep(1)

    desc_box = manager.page.locator("#description-textarea #textbox").first
    if desc_box.is_visible():
        desc_box.click()
        manager.page.keyboard.press("End")
        manager.page.keyboard.type(" ")
        time.sleep(0.3)
        manager.page.keyboard.press("Backspace")
        time.sleep(0.5)

    # 3. Dismiss any popup modal if visible
    manager.page.evaluate("""
    () => {
        const cancelBtn = Array.from(document.querySelectorAll('button, ytcp-button')).find(b => (b.innerText || '').trim() === 'Hủy' || (b.innerText || '').trim() === 'Cancel');
        if (cancelBtn) cancelBtn.click();
    }
    """)
    time.sleep(1)

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

    # 4. Click Save
    print("[*] Checking Save button...")
    save_btn = manager.page.locator("#save, ytcp-button#save-button, button:has-text('Lưu'), button:has-text('Save')").first
    if save_btn.is_visible(timeout=5000):
        is_disabled = save_btn.is_disabled()
        print(f"Save button disabled state: {is_disabled}")
        if not is_disabled:
            save_btn.click()
            print("  ✓ Clicked [LƯU] successfully!")
            time.sleep(6)
        else:
            print("  [*] Save button is disabled (no changes detected or already saved).")

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

finally:
    manager.close()
