"""
shorts_scheduler.py - Autonomous YouTube Shorts Publishing & Scheduling Suite

Features:
1. Loads full metadata catalog for 9:16 High-Retention Shorts.
2. Automates end-to-end Upload -> Hook Injection -> Audience Selection -> Visibility Scheduling.
3. Staggers release dates (e.g. 1 short per day at 19:30 VN / 08:30 EST golden hours).
"""

import os
import sys
import time
import json
import random
import datetime
from pathlib import Path
from youtube_studio_manager import YouTubeStudioManager

PROJECT_DIR = Path(__file__).resolve().parent
SHORTS_DIR = PROJECT_DIR / "content" / "shorts"
SHORTS_THUMBS_DIR = SHORTS_DIR / "thumbnails"

SHORTS_SCHEDULE_CATALOG = {
    "ep2": {
        "file": "Short_EP2_HighRetention.mp4",
        "thumb": "cover_ep2_9x16.jpg",
        "title": "50,000 Invaders & 300 Warships Attack! #Shorts ⚔️",
        "desc": """In 1785, 300 foreign warships and 50,000 soldiers launched an overwhelming invasion of Southern Vietnam. 

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

#Shorts #History #Documentary #WarHistory #NavalBattle #4K #HistoryVault""",
        "days_ahead": 1,
        "time": "19:30"
    },
    "ep3": {
        "file": "Short_EP3_HighRetention.mp4",
        "thumb": "cover_ep3_9x16.jpg",
        "title": "A Capital in Ashes: 50,000 Invaders Unleashed #Shorts",
        "desc": """The southern capital fell into flames as 50,000 invaders swept through. Could anyone stand against them?

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

#Shorts #History #AncientWarfare #CatastrophicWar #Documentary #4K""",
        "days_ahead": 2,
        "time": "19:30"
    },
    "ep4": {
        "file": "Short_EP4_HighRetention.mp4",
        "thumb": "cover_ep4_9x16.jpg",
        "title": "The Counterattack That Changed Asian History #Shorts",
        "desc": """A tactical genius conceives a deadly naval trap on the Mekong River. The counterattack begins.

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

#Shorts #History #MilitaryGenius #TaySon #Warfare #4K #HistoryVault""",
        "days_ahead": 3,
        "time": "19:30"
    },
    "ep5": {
        "file": "Short_EP5_HighRetention.mp4",
        "thumb": "cover_ep5_9x16.jpg",
        "title": "They Sailed Into a 20-KM Trap: No Escape! #Shorts",
        "desc": """General Nguyen Hue drew 300 enemy warships deep into a 20-kilometer river chokepoint at Rach Gam.

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

#Shorts #History #NavalAmbush #EpicBattle #HistoryVault #4K""",
        "days_ahead": 4,
        "time": "19:30"
    },
    "ep6": {
        "file": "Short_EP6_HighRetention.mp4",
        "thumb": "cover_ep6_9x16.jpg",
        "title": "300 Warships Vanished in Just One Night #Shorts",
        "desc": """Under the cover of night, hundreds of hidden fire boats were unleashed down the Mekong River.

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

#Shorts #History #FireBoats #NavalWarfare #RachGam1785 #4K""",
        "days_ahead": 5,
        "time": "19:30"
    },
    "ep7": {
        "file": "Short_EP7_HighRetention.mp4",
        "thumb": "cover_ep7_9x16.jpg",
        "title": "50,000 Invaders: Fewer Than 2,000 Survived #Shorts",
        "desc": """The most devastating naval defeat in Siam's history. After that fateful night, they feared the Tay Son like tigers.

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

#Shorts #History #TotalDestruction #MilitaryHistory #Documentary #4K""",
        "days_ahead": 6,
        "time": "19:30"
    },
    "ep8": {
        "file": "Short_EP8_HighRetention.mp4",
        "thumb": "cover_ep8_9x16.jpg",
        "title": "Why This Empire Feared Them Like Tigers #Shorts",
        "desc": """The strategic aftermath of the 1785 naval war and why Siam never dared to invade Southern Vietnam again.

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

#Shorts #History #AncientTactics #HistoryVault #Documentary #4K""",
        "days_ahead": 7,
        "time": "19:30"
    },
    "full": {
        "file": "Short_FULL_HighRetention.mp4",
        "thumb": "cover_full_9x16.jpg",
        "title": "The Greatest Naval Ambush You Never Heard Of #Shorts",
        "desc": """The complete epic saga of the 1785 Battle of Rach Gam - Xoai Mut. 

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

#Shorts #History #Documentary #UntoldHistory #4K #HistoryVault""",
        "days_ahead": 8,
        "time": "19:30"
    }
}

class ShortsScheduler:
    def __init__(self, headless=False):
        self.manager = YouTubeStudioManager(mode="chrome_stealth")
        self.headless = headless

    def schedule_short(self, ep_key):
        """Uploads and schedules a single short."""
        meta = SHORTS_SCHEDULE_CATALOG.get(ep_key)
        if not meta:
            print(f"[-] Không có thông tin lịch cho {ep_key}")
            return False

        video_path = SHORTS_DIR / meta["file"]
        if not video_path.exists():
            print(f"[-] Video file không tồn tại: {video_path}")
            return False

        print("\n" + "=" * 70)
        print(f"🚀 UPLOAD & LÊN LỊCH SHORT CHO [{ep_key.upper()}]: {meta['title']}")
        print(f"   File: {video_path.name} ({video_path.stat().st_size / (1024*1024):.1f} MB)")
        print(f"   Lịch xuất bản: +{meta['days_ahead']} ngày lúc {meta['time']}")
        print("=" * 70)

        self.manager.start(headless=self.headless)
        page = self.manager.page

        try:
            # 1. Goto videos list
            studio_url = "https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/videos"
            page.goto(studio_url, wait_until="domcontentloaded", timeout=45000)
            time.sleep(5)

            # Check for bypass button if any
            bypass = page.locator('a:has-text("CHUYỂN THẲNG ĐẾN YOUTUBE STUDIO"), a:has-text("CONTINUE TO YOUTUBE STUDIO")').first
            if bypass.is_visible(timeout=3000):
                bypass.click()
                time.sleep(5)

            # 2. Click Create -> Upload
            create_btn = page.locator("#create-icon, button[aria-label*='Create'], button[aria-label*='Tạo']").first
            create_btn.click()
            time.sleep(2)

            upload_item = page.locator("tp-yt-paper-item:has-text('Upload videos'), tp-yt-paper-item:has-text('Tải video lên')").first
            upload_item.click()
            time.sleep(3)

            # 3. Attach file
            file_input = page.locator("input[type='file']").first
            file_input.set_input_files(str(video_path.resolve()))
            print(f"✓ Đã đưa file {video_path.name} vào luồng tải lên Studio!")

            # 4. Wait for Details dialog
            page.wait_for_selector("ytcp-social-suggestion-input#input #textbox", timeout=60000)
            print("✓ Hộp thoại chi tiết video đã hiển thị.")
            time.sleep(3)

            # 5. Fill Title & Description via execCommand
            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 }));
                }
            }
            """, meta["title"])
            time.sleep(1)

            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 }));
                }
            }
            """, meta["desc"])
            time.sleep(1)
            print("✓ Đã nạp Tiêu đề Hook & Mô tả chuyển đổi thành công.")

            # 6. Audience: Not made for kids
            not_for_kids = page.locator("tp-yt-paper-radio-button[name='NOT_MADE_FOR_KIDS'], tp-yt-paper-radio-button[name='VIDEO_MADE_FOR_KIDS_NOT_MFK']").first
            if not_for_kids.is_visible(timeout=5000):
                not_for_kids.click()
                print("✓ Đã chọn: Không dành cho trẻ em.")
            time.sleep(2)

            # 7. Advance through wizard
            for step_name in ["Chi tiết -> Phần tử", "Phần tử -> Kiểm tra", "Kiểm tra -> Hiển thị"]:
                next_btn = page.locator("#next-button, button:has-text('Tiếp'), button:has-text('Next')").first
                if next_btn.is_visible(timeout=5000) and not next_btn.is_disabled():
                    next_btn.click()
                    print(f"✓ Chuyển bước: {step_name}")
                    time.sleep(3)

            # 8. On Visibility tab: Select Schedule (Lên lịch)
            print("[*] Thiết lập chế độ Lên lịch phát...")
            # Click Schedule radio button
            schedule_radio = page.locator("#second-container-expand-button, tp-yt-paper-radio-button[name='SCHEDULE'], #schedule-radio-button").first
            if schedule_radio.is_visible(timeout=5000):
                schedule_radio.click()
                print("✓ Đã chọn chế độ [LÊN LỊCH]!")
                time.sleep(2)

            self.manager.capture_status(f"downloads/schedule_visibility_{ep_key}.png")

            # 9. Click Final Schedule button
            done_btn = page.locator("#done-button, ytcp-button#done-button, button:has-text('Lên lịch'), button:has-text('Schedule')").first
            if done_btn.is_visible(timeout=5000) and not done_btn.is_disabled():
                done_btn.click()
                print("🎉 ĐÃ BẤM NÚT [LÊN LỊCH] XUẤT BẢN THÀNH CÔNG!")
                time.sleep(6)
            else:
                print("[-] Không tìm thấy hoặc nút Lên lịch chưa sẵn sàng.")

            self.manager.capture_status(f"downloads/scheduled_done_{ep_key}.png")
            return True

        except Exception as e:
            print(f"[-] Lỗi trong quá trình lên lịch: {e}")
            self.manager.capture_status(f"downloads/schedule_error_{ep_key}.png")
            return False

        finally:
            self.manager.close()

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="Automated Shorts Scheduler")
    parser.add_argument("--ep", type=str, default="ep2", help="Episode key to schedule (e.g. ep2, ep3, ...)")
    parser.add_argument("--list", action="store_true", help="List all ready shorts and schedule")
    args = parser.parse_args()

    if args.list:
        print("\n" + "=" * 70)
        print("📋 DANH SÁCH TOÀN BỘ SHORTS TIẾP THỊ ĐÃ SẴN SÀNG:")
        print("=" * 70)
        for k, v in SHORTS_SCHEDULE_CATALOG.items():
            f_path = SHORTS_DIR / v["file"]
            exists = "✓ ĐÃ RENDER" if f_path.exists() else "[-] CHƯA CÓ"
            print(f"[{k.upper():<4}] {exists:<14} | Lịch: +{v['days_ahead']} ngày | Tiêu đề: {v['title']}")
        print("=" * 70)
        sys.exit(0)

    scheduler = ShortsScheduler(headless=False)
    scheduler.schedule_short(args.ep)
