import os
import sys
import glob
import json
import time
from youtube_uploader import get_youtube_service
from googleapiclient.http import MediaFileUpload

if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass

SHORTS_METADATA = {
    "ep1_short_1": {
        "title": "The Prince Who Lost Everything (1785) #Shorts",
        "description": "Facing total defeat, Lord Nguyen Anh made a desperate choice that changed Asian history.\n\n#Shorts #HistoryVault #UntoldBattles #AncientWarfare"
    },
    "ep1_short_2": {
        "title": "The Secret Alliance with Siam #Shorts",
        "description": "300 warships and 50,000 soldiers enter the fray. The storm begins.\n\n#Shorts #HistoryVault #NavalHistory #Warfare"
    },
    "ep2_short_1": {
        "title": "50,000 Troops Invade the Mekong Delta #Shorts",
        "description": "The massive Siamese armada arrives in Southern Vietnam.\n\n#Shorts #HistoryVault #UntoldHistory"
    },
    "ep2_short_2": {
        "title": "The Siamese War Fleet in Action #Shorts",
        "description": "300 Siamese warships move down the river.\n\n#Shorts #HistoryVault #NavalWarfare"
    },
    "ep3_short_1": {
        "title": "The Fall of Gia Dinh: A Land in Flames #Shorts",
        "description": "The devastating invasion pushes the southern defenders to the brink.\n\n#Shorts #HistoryVault #EpicHistory"
    },
    "ep3_short_2": {
        "title": "Desperate Resistance in Southern Vietnam #Shorts",
        "description": "Outnumbered and outgunned, the resistance fights for survival.\n\n#Shorts #HistoryVault #WarDocumentary"
    },
    "ep4_short_1": {
        "title": "General Nguyen Hue: The Gathering Storm #Shorts",
        "description": "Military genius Nguyen Hue marches south for the counteroffensive.\n\n#Shorts #HistoryVault #MilitaryGenius #GreatCommanders"
    },
    "ep4_short_2": {
        "title": "Tay Son Warships Mobilize #Shorts",
        "description": "The elite Tay Son battle fleet prepares for the ultimate clash.\n\n#Shorts #HistoryVault #WarHistory"
    },
    "ep5_short_1": {
        "title": "The Deadliest River Trap in History (1785) #Shorts",
        "description": "Nguyen Hue inspects the Tien River and designs the fatal ambush.\n\n#Shorts #HistoryVault #SalamisOfTheEast #Ambush"
    },
    "ep5_short_2": {
        "title": "Luring 300 Warships into the Narrow Strait #Shorts",
        "description": "The Siamese armada enters the Rach Gam gorge, unaware of the trap.\n\n#Shorts #HistoryVault #MilitaryTactics"
    },
    "ep6_short_1": {
        "title": "Night of Fire: The Ambush Begins #Shorts",
        "description": "Tay Son fire ships launch into the trapped Siamese armada.\n\n#Shorts #HistoryVault #FireShips #NavalAmbush"
    },
    "ep6_short_2": {
        "title": "300 Warships Burned to the Waterline #Shorts",
        "description": "The catastrophic destruction of the invading fleet in one fateful night.\n\n#Shorts #HistoryVault #CatastrophicDefeat"
    },
    "ep7_short_1": {
        "title": "The Annihilation of Siam's Fleet #Shorts",
        "description": "'After that night, they feared the Tay Son like tigers.'\n\n#Shorts #HistoryVault #EpicBattles"
    },
    "ep7_short_2": {
        "title": "The Tiger of Vietnam: Nguyen Hue #Shorts",
        "description": "The battle that cemented General Nguyen Hue's legendary status.\n\n#Shorts #HistoryVault #AsianHistory"
    },
    "ep8_short_1": {
        "title": "Lessons of the 1785 River War #Shorts",
        "description": "The strategic legacy of the battle that preserved sovereignty.\n\n#Shorts #HistoryVault #HistoricalStrategy"
    },
    "ep8_short_2": {
        "title": "The Legacy of Forgotten Battles #Shorts",
        "description": "Subscribe to The Historical Vault for more untold military history!\n\n#Shorts #HistoryVault #Documentary"
    }
}

STATE_FILE = "uploaded_shorts.json"

def upload_short(video_path, title, description, privacy='public'):
    youtube = get_youtube_service()
    tags = ["Shorts", "History Vault", "history documentary", "untold battles", "ancient warfare", "naval battles", "military history"]
    
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags,
            'categoryId': '27'
        },
        'status': {
            'privacyStatus': privacy,
            'selfDeclaredMadeForKids': False
        }
    }
    
    media = MediaFileUpload(video_path, chunksize=-1, resumable=True, mimetype='video/mp4')
    print(f"\n[Upload Short] {title} ({os.path.basename(video_path)})...")
    
    request = youtube.videos().insert(
        part=','.join(body.keys()),
        body=body,
        media_body=media
    )
    
    response = None
    while response is None:
        status, response = request.next_chunk()
        if status:
            print(f"Tiến độ: {int(status.progress() * 100)}%")
            
    video_id = response['id']
    print(f" [OK] Upload Short thành công! ID: {video_id} (Link: https://youtube.com/shorts/{video_id})")
    return video_id

def main():
    shorts_files = sorted(glob.glob("content/shorts/*.mp4"))
    if not shorts_files:
        print("Không tìm thấy file shorts trong content/shorts/")
        return
        
    uploaded = {}
    if os.path.exists(STATE_FILE):
        try:
            with open(STATE_FILE, "r", encoding="utf-8") as f:
                uploaded = json.load(f)
        except Exception:
            pass
            
    print(f"=== TÌM THẤY {len(shorts_files)} VIDEO SHORTS TRONG content/shorts ===")
    
    # Upload mẫu short đầu tiên hoặc upload theo chỉ định
    for s_path in shorts_files:
        base_key = os.path.splitext(os.path.basename(s_path))[0]
        if base_key in uploaded:
            print(f"[ĐÃ UPLOAD] {base_key} (ID: {uploaded[base_key]['video_id']}) - Bỏ qua.")
            continue
            
        meta = SHORTS_METADATA.get(base_key, {
            "title": f"Untold History Epic Battles #Shorts",
            "description": "Watch epic untold history on The Historical Vault!\n\n#Shorts #HistoryVault"
        })
        
        # Chỉ upload 1 hoặc 2 short nếu chạy manual, hoặc chạy toàn bộ
        vid_id = upload_short(s_path, meta["title"], meta["description"], privacy='public')
        if vid_id:
            uploaded[base_key] = {
                "video_id": vid_id,
                "title": meta["title"],
                "short_url": f"https://youtube.com/shorts/{vid_id}",
                "uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            with open(STATE_FILE, "w", encoding="utf-8") as f:
                json.dump(uploaded, f, indent=2, ensure_ascii=False)
                
            # Nghỉ ngắn giữa các lần upload
            time.sleep(3)
            
if __name__ == "__main__":
    main()
