import os
import sys
import json
import time
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
UPLOADED_JSON = PROJECT_DIR / "uploaded_episodes.json"
METADATA_JSON = PROJECT_DIR / "extension" / "metadata.json"
PLAYLIST_ID = "PLZBnH5iYlu-w"

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

EPISODES_TO_UPLOAD = [
    {
        "ep": 7,
        "video_path": PROJECT_DIR / "content" / "videos_4k" / "ep7_4k.mp4",
        "thumb_path": PROJECT_DIR / "content" / "thumbnails_4k" / "ep7_thumb_4k.jpg",
        "subtitles_dir": PROJECT_DIR / "content" / "subtitles" / "ep7",
        "publish_time": datetime.datetime(2026, 10, 14, 12, 0, 0), # 19:00 VN, Wednesday 14/10/2026
        "title": "The Annihilation: Siam's Greatest Naval Disaster | Forgotten Battles Ep 7 [4K UHD]",
        "description": """In less than a single day, almost the entire invading armada of 300 warships was obliterated. Out of 50,000 Siamese soldiers, only a few thousand survivors escaped through the wilderness back to Bangkok. As contemporary Siamese royal chronicles recorded: "After that defeat, the Siamese feared the Tay Son like tigers."

Episode 7 examines the immense scale of the defeat, the desperate retreat through the jungle, and its psychological impact on the regional balance of power.

🔥 BINGE THE FULL 4K SERIES IN ORDER:
👉 https://www.youtube.com/playlist?list=PLZBnH5iYlu-w

⏱️ CHAPTER TIMESTAMPS:
00:00 - The Morning After the Inferno
00:50 - The Retreat Through the Jungles
01:40 - Survivors Return to Bangkok
02:30 - "Fearing the Tay Son Like Tigers"
03:00 - Regional Balance of Power Shift

🎬 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
• Episode 4: https://www.youtube.com/watch?v=O-8w_ONx3as
• Episode 5: https://www.youtube.com/watch?v=lygtPzWC7Ig
• Episode 6: https://www.youtube.com/watch?v=UOaAm7zVOV4

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

#HistoryVault #HistoricalBattles #CatastrophicDefeat #SiamHistory #MilitaryConsequences #TaySon #NguyenHue #AncientWarfare #VietnamHistory #Documentary4K""",
        "tags": [
            "Siamese disaster",
            "battle aftermath",
            "Rach Gam aftermath",
            "total naval annihilation",
            "Tay Son tigers",
            "Bangkok chronicles 1785",
            "regional warfare",
            "decisive military victory",
            "4k history",
            "Nguyen Hue",
            "Emperor Quang Trung",
            "naval warfare",
            "Forgotten Battles",
            "History Vault"
        ]
    },
    {
        "ep": 8,
        "video_path": PROJECT_DIR / "content" / "videos_4k" / "ep8_4k.mp4",
        "thumb_path": PROJECT_DIR / "content" / "thumbnails_4k" / "ep8_thumb_4k.jpg",
        "subtitles_dir": PROJECT_DIR / "content" / "subtitles" / "ep8",
        "publish_time": datetime.datetime(2026, 10, 15, 12, 0, 0), # 19:00 VN, Thursday 15/10/2026
        "title": "The Strategic Legacy: Lessons of the 1785 Naval War | Forgotten Battles Ep 8 [4K UHD]",
        "description": """The Battle of Rach Gam - Xoai Mut in 1785 permanently secured the southern territory and established river defense doctrines studied to this day. Though Lord Nguyen Anh would eventually return decades later to establish the Nguyen Dynasty, the tactical brilliance displayed in 1785 remains an enduring testament to national resilience and military genius.

The grand series finale of "Untold Battles: The 1785 Mekong Naval War".

🔥 BINGE THE FULL 4K SERIES IN ORDER:
👉 https://www.youtube.com/playlist?list=PLZBnH5iYlu-w

⏱️ CHAPTER TIMESTAMPS:
00:00 - Securing the Southern Frontier
01:05 - The Long Journey of Nguyen Anh
02:10 - Tactical Doctrines of River Defense
03:05 - The Enduring Legacy of 1785

🎬 COMPLETE SERIES 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
• Episode 4: https://www.youtube.com/watch?v=O-8w_ONx3as
• Episode 5: https://www.youtube.com/watch?v=lygtPzWC7Ig
• Episode 6: https://www.youtube.com/watch?v=UOaAm7zVOV4

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

#HistoryVault #MilitaryStrategy #HistoryDocumentary #Sovereignty #SeriesFinale4K #NguyenHue #QuangTrung #VietnamHistory #AncientWarfare""",
        "tags": [
            "military strategy",
            "river defense doctrines",
            "legacy of 1785",
            "Nguyen Dynasty origin",
            "Quang Trung legacy",
            "ancient military doctrine",
            "series finale",
            "historical documentary 4k",
            "The Historical Vault",
            "Nguyen Hue",
            "Rach Gam Xoai Mut",
            "tactical brilliance"
        ]
    }
]

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

def upload_single_episode(youtube, ep_data):
    ep = ep_data["ep"]
    title = ep_data["title"]
    desc = ep_data["description"]
    tags = ep_data["tags"]
    pub_time = ep_data["publish_time"]
    vpath = ep_data["video_path"]
    tpath = ep_data["thumb_path"]
    sdir = ep_data["subtitles_dir"]

    print("\n" + "=" * 70)
    print(f"🚀 BẮT ĐẦU UPLOAD TẬP {ep}: {title}")
    print(f"   Video:       {vpath.name} ({vpath.stat().st_size / (1024*1024):.1f} MB)")
    print(f"   Lên lịch:    {pub_time.isoformat()}Z (19:00 VN, {pub_time.strftime('%d/%m/%Y')})")
    print(f"   Thumbnail:   {tpath.name} ({tpath.stat().st_size / (1024*1024):.2f} MB)")
    print("=" * 70)

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

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

    print(f"[1/5] Đang upload video 4K Tập {ep}...")
    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 % 20 == 0:
                print(f"  -> Tiến độ upload Tập {ep}: {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(f"\n[2/5] Đang upload Thumbnail 4K UHD Tập {ep}...")
    try:
        thumb_req = youtube.thumbnails().set(
            videoId=video_id,
            media_body=MediaFileUpload(str(tpath), 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: {e}")

    # 3. Upload Subtitles
    print(f"\n[3/5] Đang upload 6 bộ phụ đề đa ngôn ngữ Tập {ep}...")
    for lang_code, lang_name in SUBTITLE_MAP.items():
        srt_file = sdir / f"ep{ep}_{lang_code}.srt"
        if not srt_file.exists():
            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}")
        except Exception as e:
            print(f"  [-] Lỗi upload phụ đề {lang_code}: {e}")

    # 4. Thêm vào Official Series Playlist
    print(f"\n[4/5] Đang thêm Tập {ep} vào Official Series Playlist...")
    try:
        pl_body = {
            "snippet": {
                "playlistId": PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": video_id
                }
            }
        }
        pl_req = youtube.playlistItems().insert(
            part="snippet",
            body=pl_body
        )
        pl_resp = pl_req.execute()
        print(f"✓ Đã thêm Tập {ep} vào Playlist {PLAYLIST_ID}! (Item ID: {pl_resp['id']})")
    except Exception as e:
        print(f"[-] Lỗi thêm vào Playlist: {e}")

    # 5. Cập nhật state tracking files
    print(f"\n[5/5] 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[str(ep)] = {
            "video_id": video_id,
            "title": title,
            "status": "uploaded",
            "schedule": f"{pub_time.strftime('%Y-%m-%d')} 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 str(ep) in meta_dict:
                meta_dict[str(ep)]["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(f"  ✓ Đã đồ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}")

    return video_id

def main():
    youtube = get_youtube_service()
    for ep_data in EPISODES_TO_UPLOAD:
        upload_single_episode(youtube, ep_data)
        time.sleep(5)

    print("\n" + "=" * 70)
    print("🎉 HOÀN THÀNH XUẤT SẮC TOÀN BỘ 8 TẬP CỦA SERIES 1785 NAVAL WAR!")
    print("   Toàn bộ lịch phát sóng từ Tập 1 đến Tập 8 đã được kích hoạt 100% tự động!")
    print("=" * 70)

if __name__ == "__main__":
    main()
