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

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

VIDEO_PATH = r"content\videos_4k\Forgotten_Battles_1785_Full_4K.mp4"
THUMBNAIL_PATH = r"content\thumbnails\full_movie_thumb.jpg"
STATE_FILE = "full_movie_upload_state.json"

TITLE = "The Battle of Rach Gam (1785): The Complete 1785 Naval War | Full Documentary [4K UHD]"

DESCRIPTION = """The definitive 4K UHD documentary of the 1785 Battle of Rach Gam - Xoai Mut: from the exile of Lord Nguyen Anh and the massive Siamese invasion of 50,000 soldiers, to General Nguyen Hue's masterstroke ambush that destroyed 300 enemy warships in a single night.

Presented in full 4K UHD cinema omnibus format with complete chapter markers and spatial audio.

⏱️ FULL MOVIE CHAPTERS:
00:00:00 - Chapter 1: The Exiled Prince & The Desperate Alliance
00:04:40 - Chapter 2: 50,000 Invaders: The Siamese Fleet Dominates the River
00:09:30 - Chapter 3: A Nation in Flames: The Fall of Gia Dinh
00:14:00 - Chapter 4: The Tiger Awakens: General Nguyen Hue Strikes Back
00:19:50 - Chapter 5: The Deadliest River Trap in Military History: Rach Gam (1785)
00:24:30 - Chapter 6: Night of Fire: The Fire Ships Unleashed
00:28:40 - Chapter 7: The Annihilation: Blood and Ash on the River
00:32:00 - Chapter 8: Strategic Legacy: Sovereignty and Geopolitics in 1785

🔔 SUBSCRIBE to The Historical Vault for weekly epic military documentaries:
https://www.youtube.com/@TheHistoricalVault?sub_confirmation=1

#HistoryVault #FullDocumentary #AncientWarfare #NavalBattles #RachGam1785 #MilitaryHistory #Documentary4K #QuangTrung"""

TAGS = [
    "History Vault", "full documentary 4k", "Rach Gam 1785", "ancient warfare",
    "naval battles", "military history", "Asian history", "Tay Son rebellion",
    "Nguyen Hue", "Quang Trung", "Siamese armada", "fire ships ambush",
    "complete series", "epic history", "documentary omnibus"
]

def upload_full_movie():
    if not os.path.exists(VIDEO_PATH):
        print(f"[-] Không tìm thấy file video: {VIDEO_PATH}")
        return None

    if os.path.exists(STATE_FILE):
        try:
            with open(STATE_FILE, "r", encoding="utf-8") as f:
                state = json.load(f)
                if state.get("status") == "uploaded":
                    print(f"[*] Bộ Full Movie đã được upload trước đó. Video ID: {state.get('video_id')}")
                    return state.get("video_id")
        except Exception:
            pass

    size_gb = os.path.getsize(VIDEO_PATH) / (1024 * 1024 * 1024)
    print("==========================================================")
    print("TIẾN TRÌNH UPLOAD FULL MOVIE 4K (8 TẬP TRỌN BỘ)")
    print(f"File:      {VIDEO_PATH} ({size_gb:.2f} GB)")
    print(f"Chế độ:    PRIVATE (Riêng tư - Chờ phát hành sau chuỗi 8 tập)")
    print(f"Tiêu đề:   {TITLE}")
    print("==========================================================")

    youtube = get_youtube_service()

    body = {
        'snippet': {
            'title': TITLE,
            'description': DESCRIPTION,
            'tags': TAGS,
            'categoryId': '27' # Education
        },
        'status': {
            'privacyStatus': 'private', # PRIVATE theo đúng yêu cầu
            'selfDeclaredMadeForKids': False
        }
    }

    # Resumable upload chunksize 64MB cho file lớn 5.4GB
    chunk_size = 64 * 1024 * 1024
    media = MediaFileUpload(VIDEO_PATH, chunksize=chunk_size, resumable=True, mimetype='video/mp4')

    request = youtube.videos().insert(
        part=','.join(body.keys()),
        body=body,
        media_body=media
    )

    print("[*] Đang bắt đầu truyền tải video 5.4GB lên YouTube...")
    response = None
    start_time = time.time()

    while response is None:
        try:
            status, response = request.next_chunk()
            if status:
                pct = int(status.progress() * 100)
                speed_mb = (status.progress() * size_gb * 1024) / max(1.0, (time.time() - start_time))
                print(f"[*] Tiến độ tải lên: {pct}% ({speed_mb:.1f} MB/s)", flush=True)
        except Exception as e:
            print(f"[-] Lỗi upload: {e}")
            raise e

    video_id = response['id']
    print(f"\n✓ TẢI LÊN THÀNH CÔNG! Video ID: {video_id}")
    print(f"✓ Link quản lý video (Private): https://studio.youtube.com/video/{video_id}/edit")

    # Gắn Thumbnail 4K
    if os.path.exists(THUMBNAIL_PATH):
        try:
            print("[*] Đang gắn thumbnail Full Movie...")
            set_thumbnail(video_id, THUMBNAIL_PATH)
            print("✓ Đã gắn thumbnail Full Movie thành công!")
        except Exception as e:
            print(f"[-] Lỗi gắn thumbnail: {e}")

    # Ghi nhận trạng thái
    state_data = {
        "video_id": video_id,
        "title": TITLE,
        "status": "uploaded",
        "privacy": "private",
        "uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "studio_url": f"https://studio.youtube.com/video/{video_id}/edit",
        "video_url": f"https://youtu.be/{video_id}"
    }
    with open(STATE_FILE, "w", encoding="utf-8") as f:
        json.dump(state_data, f, indent=2, ensure_ascii=False)

    return video_id

if __name__ == "__main__":
    upload_full_movie()
