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 with Viral Hook
    new_title = "Zero Warships. Exiled Prince. How Did He Survive? ⚔️ #Shorts"
    print(f"[*] Updating Title to: {new_title}")
    title_box = manager.page.locator("#textbox[aria-label*='tiêu đề'], #textbox[aria-label*='title'], #title-textarea #textbox").first
    if title_box.is_visible(timeout=5000):
        title_box.click()
        manager.page.keyboard.press("Control+A")
        manager.page.keyboard.press("Backspace")
        time.sleep(0.5)
        manager.page.keyboard.type(new_title, delay=15)
        print("  ✓ Title updated.")

    # 2. Update Description with CTA Funnel
    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...")
    desc_box = manager.page.locator("#description-textarea #textbox, #textbox[aria-label*='mô tả'], #textbox[aria-label*='description']").first
    if desc_box.is_visible(timeout=5000):
        desc_box.click()
        manager.page.keyboard.press("Control+A")
        manager.page.keyboard.press("Backspace")
        time.sleep(0.5)
        manager.page.evaluate("""
        (text) => {
            const el = document.querySelector('#description-textarea #textbox');
            if (el) {
                el.innerText = text;
                el.dispatchEvent(new Event('input', { bubbles: true }));
            }
        }
        """, new_desc)
        print("  ✓ Description updated.")

    # 3. Test Related Video Selection
    print("[*] Opening Related Video selector...")
    manager.page.evaluate("""
    () => {
        const triggers = Array.from(document.querySelectorAll('ytcp-dropdown-trigger'));
        const relatedTrigger = triggers.find(t => (t.innerText || '').includes('Video có liên quan'));
        if (relatedTrigger) {
            relatedTrigger.click();
        }
    }
    """)
    time.sleep(3)
    manager.capture_status("downloads/studio_short_related_dialog.png")

    # Inspect dialog for selecting video
    dialog_info = manager.page.evaluate("""
    () => {
        const dialog = document.querySelector('ytcp-video-pick-dialog, ytcp-dialog, tp-yt-paper-dialog[opened]');
        if (!dialog) return { opened: false };
        const rows = Array.from(dialog.querySelectorAll('ytcp-video-row, ytcp-entity-row, .row, #entity-row')).map(r => ({
            text: (r.innerText || '').replace(/\\n+/g, ' ').substring(0, 100)
        }));
        const searchInput = dialog.querySelector('input, #search-input');
        return {
            opened: true,
            title: (dialog.querySelector('#dialog-title, h2') || {}).innerText,
            rows: rows.slice(0, 10),
            hasSearch: !!searchInput
        };
    }
    """)
    print("Related video dialog info:", dialog_info)

    # If dialog opened, select the Full Movie (c8Akru2j7ok) or EP1
    if dialog_info.get('opened'):
        print("[*] Selecting Full Movie or EP1 from dialog...")
        selected = manager.page.evaluate("""
        () => {
            const dialog = document.querySelector('ytcp-video-pick-dialog, ytcp-dialog, tp-yt-paper-dialog[opened]');
            if (!dialog) return false;
            // Find row containing "Forgotten Battles" or "Full Documentary" or "Ep 1"
            const rows = Array.from(dialog.querySelectorAll('ytcp-video-row, ytcp-entity-row, .row, #entity-row'));
            const targetRow = rows.find(r => {
                const txt = (r.innerText || '').toLowerCase();
                return txt.includes('full') || txt.includes('battles') || txt.includes('forgotten');
            }) || rows[0];
            
            if (targetRow) {
                targetRow.click();
                return targetRow.innerText.replace(/\\n+/g, ' ').substring(0, 80);
            }
            return false;
        }
        """)
        print("  ✓ Selected related video:", selected)
        time.sleep(2)

    # 4. Try Thumbnail upload via file-loader
    thumb_path = str(Path("content/shorts/thumbnails/cover_ep1_9x16.jpg").resolve())
    if os.path.exists(thumb_path):
        print(f"[*] Attempting thumbnail upload: {thumb_path}")
        try:
            # Unhide custom-still-editor if hidden
            manager.page.evaluate("""
            () => {
                const ed = document.querySelector('ytcp-video-custom-still-editor');
                if (ed) {
                    ed.removeAttribute('hidden');
                    ed.style.display = 'block';
                }
            }
            """)
            file_input = manager.page.locator("input#file-loader").first
            if file_input.count() > 0:
                file_input.set_input_files(thumb_path)
                print("  ✓ set_input_files called.")
                time.sleep(3)
        except Exception as e:
            print("  [-] Thumbnail upload exception:", e)

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

    # 5. Save changes
    print("[*] Saving changes...")
    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):
        print("Save button disabled?:", save_btn.is_disabled())
        if not save_btn.is_disabled():
            save_btn.click()
            print("  ✓ Clicked SAVE!")
            time.sleep(5)
        else:
            print("  [*] Save button disabled (no changes or already saved).")

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

finally:
    manager.close()
