import os
import sys
import json
import datetime
from pathlib import Path
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

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

PROJECT_DIR = Path(__file__).resolve().parent
VIDEO_PATH = PROJECT_DIR / "content" / "videos_4k" / "ep4_4k.mp4"
THUMBNAIL_PATH = PROJECT_DIR / "content" / "thumbnails_4k" / "ep4_thumb_4k.jpg"
SUBTITLES_DIR = PROJECT_DIR / "content" / "subtitles" / "ep4"
UPLOADED_JSON = PROJECT_DIR / "uploaded_episodes.json"
METADATA_JSON = PROJECT_DIR / "extension" / "metadata.json"

TITLE = "Tayson Strikes Back: The Gathering Storm | Forgotten Battles Ep 4 [4K UHD]"

DESCRIPTION = """Receiving urgent distress calls from the South, Supreme Commander Nguyen Hue mobilized the veteran Tay Son battle fleet and sailed south in secret. Arriving in My Tho, he refused to engage in an open head-on clash against superior numbers, choosing instead to outsmart his enemies through battlefield geography and meticulous tactical preparation.

Episode 4 details the masterclass in military mobilization that set the stage for one of history's greatest naval ambushes at Rach Gam - Xoai Mut.

⏱️ CHAPTER TIMESTAMPS:
00:00 - The Messenger Reaches Quy Nhon
01:20 - Nguyen Hue Mobilizes the Battle Fleet
02:45 - The Secret Voyage South
04:00 - Arrival at My Tho
05:10 - The Genius Begins His Calculations

🎬 PREVIOUS EPISODES:
• Episode 1: https://www.youtube.com/watch?v=DT202N1I4-A
• Episode 2: https://www.youtube.com/watch?v=FKPhXdwFbII
• Episode 3: https://www.youtube.com/watch?v=gZ40mP451Rc

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

#HistoryVault #MilitaryTactics #GreatCommanders #NguyenHue #NavalFleet #QuangTrung #AncientWarfare #TaySon #Documentary4K #VietnamHistory"""

TAGS = [
    "Nguyen Hue",
    "Emperor Quang Trung",
    "military genius",
    "Tay Son counteroffensive",
    "great commanders in history",
    "naval mobilization",
    "ancient military tactics",
    "4k documentary",
    "Asian commanders",
    "History Vault",
    "Forgotten Battles",
    "1785 naval war",
    "Battle of Rach Gam",
    "Siamese invasion",
    "Vietnam history",
    "military strategy",
    "epic history documentary",
    "naval warfare",
    "Southeast Asia history"
]

# Schedule for Tomorrow: 2026-10-11 at 19:00:00 VN Time (12:00:00 UTC)
PUBLISH_TIME_UTC = datetime.datetime(2026, 10, 11, 12, 0, 0)

SUBTITLE_MAP = {
    'vi': 'Tiếng Việt (Bản ngữ)',
    'en': 'English (Official)',
    'de': 'Deutsch',
    'fr': 'Français',
    'es': 'Español',
    'ja': '日本語'
}

def get_youtube_service():
    creds = Credentials.from_authorized_user_file('token.json')
    return build('youtube', 'v3', credentials=creds)

def main():
    print("=" * 70)
    print("🚀 BẮT ĐẦU UPLOAD TẬP 4 VỚI TRỌN BỘ TỐI ƯU HÓA SEO ĐIỆN ẢNH")
    print(f"   Video:       {VIDEO_PATH.name} ({VIDEO_PATH.stat().st_size / (1024*1024):.1f} MB)")
    print(f"   Tiêu đề:     {TITLE}")
    print(f"   Lên lịch:    {PUBLISH_TIME_UTC.isoformat()}Z (19:00 VN, 11/10/2026)")
    print(f"   Thumbnail:   {THUMBNAIL_PATH.name} ({THUMBNAIL_PATH.stat().st_size / (1024*1024):.2f} MB)")
    print("=" * 70)

    youtube = get_youtube_service()

    body = {
        'snippet': {
            'title': TITLE,
            'description': DESCRIPTION,
            'tags': TAGS,
            'categoryId': '27' # Education
        },
        'status': {
            'privacyStatus': 'private',
            'publishAt': PUBLISH_TIME_UTC.isoformat() + 'Z',
            'selfDeclaredMadeForKids': False
        }
    }

    media = MediaFileUpload(str(VIDEO_PATH), chunksize=10*1024*1024, resumable=True)

    print("\n[1/4] Đang upload video 4K lên YouTube...")
    request = youtube.videos().insert(
        part=','.join(body.keys()),
        body=body,
        media_body=media
    )

    response = None
    last_prog = -1
    while response is None:
        status, response = request.next_chunk()
        if status:
            prog = int(status.progress() * 100)
            if prog != last_prog and prog % 10 == 0:
                print(f"  -> Tiến độ upload: {prog}%")
                last_prog = prog

    video_id = response['id']
    print(f"✓ Upload video thành công! Video ID: {video_id}")
    print(f"  URL: https://youtu.be/{video_id}")

    # 2. Upload Thumbnail
    print("\n[2/4] Đang upload Thumbnail 4K UHD Obsidian Gold...")
    try:
        thumb_req = youtube.thumbnails().set(
            videoId=video_id,
            media_body=MediaFileUpload(str(THUMBNAIL_PATH), mimetype='image/jpeg')
        )
        thumb_req.execute()
        print(f"✓ Cập nhật Thumbnail 4K UHD thành công!")
    except Exception as e:
        print(f"[-] Lỗi upload thumbnail qua API: {e}")

    # 3. Upload Subtitles
    print("\n[3/4] Đang upload 6 bộ phụ đề đa ngôn ngữ...")
    for lang_code, lang_name in SUBTITLE_MAP.items():
        srt_file = SUBTITLES_DIR / f"ep4_{lang_code}.srt"
        if not srt_file.exists():
            print(f"  [-] Không thấy file phụ đề: {srt_file.name}")
            continue

        cap_body = {
            'snippet': {
                'videoId': video_id,
                'language': lang_code,
                'name': lang_name,
                'isDraft': False
            }
        }
        cap_media = MediaFileUpload(str(srt_file), mimetype='application/x-subrip')
        try:
            cap_req = youtube.captions().insert(
                part='snippet',
                sync=False,
                body=cap_body,
                media_body=cap_media
            )
            cap_resp = cap_req.execute()
            print(f"  ✓ Đã upload phụ đề [{lang_code}]: {lang_name} (ID: {cap_resp['id']})")
        except Exception as e:
            print(f"  [-] Lỗi upload phụ đề {lang_code}: {e}")

    # 4. Update state tracking files
    print("\n[4/4] Cập nhật metadata hệ thống...")
    try:
        up_data = {}
        if UPLOADED_JSON.exists():
            with open(UPLOADED_JSON, 'r', encoding='utf-8') as f:
                up_data = json.load(f)
        up_data["4"] = {
            "video_id": video_id,
            "title": TITLE,
            "status": "uploaded",
            "schedule": "2026-10-11 12:00 UTC"
        }
        with open(UPLOADED_JSON, 'w', encoding='utf-8') as f:
            json.dump(up_data, f, indent=2, ensure_ascii=False)
        print("  ✓ Đã ghi nhận vào uploaded_episodes.json")
    except Exception as e:
        print(f"[-] Lỗi cập nhật uploaded_episodes.json: {e}")

    try:
        if METADATA_JSON.exists():
            with open(METADATA_JSON, 'r', encoding='utf-8') as f:
                meta_dict = json.load(f)
            if "4" in meta_dict:
                meta_dict["4"]["video_id"] = video_id
                with open(METADATA_JSON, 'w', encoding='utf-8') as f:
                    json.dump(meta_dict, f, indent=2, ensure_ascii=False)
                print("  ✓ Đã đồng bộ video_id vào extension/metadata.json")
    except Exception as e:
        print(f"[-] Lỗi cập nhật extension/metadata.json: {e}")

    print("\n" + "=" * 70)
    print("🎉 HOÀN THÀNH XUẤT SẮC QUY TRÌNH UPLOAD TẬP 4!")
    print(f"   Video ID:    {video_id}")
    print(f"   Chế độ:      Đã lên lịch (Schedule) - 19:00 Chủ Nhật, 11/10/2026")
    print(f"   Studio Link: https://studio.youtube.com/video/{video_id}/edit")
    print("=" * 70)

if __name__ == "__main__":
    main()
