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)

    new_title = "Zero Warships. Exiled Prince. How Did He Survive? ⚔️ #Shorts"
    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"""

    # 1. Update Title via textboxes[0]
    print(f"[*] Updating Title (box 0) to: {new_title}...")
    manager.page.evaluate("""
    (titleText) => {
        const tb = document.querySelectorAll('ytcp-social-suggestion-input#input #textbox')[0];
        if (tb) {
            tb.focus();
            document.execCommand('selectAll', false, null);
            document.execCommand('insertText', false, titleText);
            tb.dispatchEvent(new Event('input', { bubbles: true }));
            tb.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
    """, new_title)
    time.sleep(1)

    # 2. Update Description via textboxes[1]
    print("[*] Updating Description (box 1)...")
    manager.page.evaluate("""
    (descText) => {
        const tb = document.querySelectorAll('ytcp-social-suggestion-input#input #textbox')[1];
        if (tb) {
            tb.focus();
            document.execCommand('selectAll', false, null);
            document.execCommand('insertText', false, descText);
            tb.dispatchEvent(new Event('input', { bubbles: true }));
            tb.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
    """, new_desc)
    time.sleep(1)

    # 3. Check values
    status = manager.page.evaluate("""
    () => {
        const boxes = document.querySelectorAll('ytcp-social-suggestion-input#input #textbox');
        return {
            title: boxes[0] ? boxes[0].innerText : null,
            titleLen: boxes[0] ? boxes[0].innerText.length : 0,
            descLen: boxes[1] ? boxes[1].innerText.length : 0
        };
    }
    """)
    print("Updated values status:", status)

    manager.capture_status("downloads/studio_short_after_input.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?: {is_disabled}")
        if not is_disabled:
            save_btn.click()
            print("  ✓ Clicked [LƯU] successfully!")
            time.sleep(6)
        else:
            print("  [*] Save button is disabled.")

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

finally:
    manager.close()
