import os
import re
import sys
import glob
import json
import datetime
from subtitle_generator import generate_english_subtitles
from thumbnail_generator import create_episode_thumbnail
from youtube_uploader import upload_video, upload_subtitle, set_thumbnail
from multilingual_subtitles import generate_multilingual_subtitles_for_ep

# Hỗ trợ in tiếng Việt trên console Windows
if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except Exception:
        pass

# Tiêu đề & mô tả tối ưu SEO lịch sử cho từng tập
EPISODE_METADATA = {
    1: {
        "title": "The Exiled Prince & The Foreign Alliance (1785) | Forgotten Battles Ep 1",
        "badge_title": "PRINCE IN EXILE",
        "description": "Episode 1 of the Untold Battles documentary series: Lord Nguyen Anh, facing the unstoppable surge of the Tay Son rebellions, seeks a desperate military alliance with the Kingdom of Siam.\n\n🔔 Subscribe to History Vault for weekly epic historical documentaries!\n#HistoryVault #UntoldHistory #AncientWarfare #NavalBattles #AsianHistory"
    },
    2: {
        "title": "50,000 Invaders: The Siamese Fleet Invades the South | Forgotten Battles Ep 2",
        "badge_title": "50,000 INVADERS",
        "description": "Episode 2: 300 Siamese warships and an army of 50,000 soldiers launch a massive invasion into Southern Vietnam, threatening to carve up the empire.\n\n#HistoryVault #Warfare #NavalHistory #HistoricalDocumentary"
    },
    3: {
        "title": "The Fall of Gia Dinh: A Nation in Flames | Forgotten Battles Ep 3",
        "badge_title": "LAND IN FLAMES",
        "description": "Episode 3: The devastating impact of the coalition army and the desperate resistance of Southern Vietnam on the brink of total collapse.\n\n#HistoryVault #AncientWarfare #EpicHistory"
    },
    4: {
        "title": "Tayson Strikes Back: The Gathering Storm | Forgotten Battles Ep 4",
        "badge_title": "THE COUNTERATTACK",
        "description": "Episode 4: Facing overwhelming foreign invaders, General Nguyen Hue mobilizes the legendary Tay Son army for a counteroffensive that will define the era.\n\n#HistoryVault #MilitaryTactics #GreatCommanders"
    },
    5: {
        "title": "The River Trap: The Ambush at Rach Gam (1785) | Forgotten Battles Ep 5",
        "badge_title": "THE RIVER AMBUSH",
        "description": "Episode 5: Military genius Nguyen Hue inspects the Tien River and designs one of the deadliest naval fire traps in world military history.\n\n#HistoryVault #MilitaryHistory #TacticalGenius #SalamisOfTheEast"
    },
    6: {
        "title": "Night of Fire: The Destruction of 300 Warships | Forgotten Battles Ep 6",
        "badge_title": "THE FIRE BOATS",
        "description": "Episode 6: The fateful night on the Mekong Delta: Tay Son fire ships unleash fury, ripping through the elite Siamese armada in hours.\n\n#HistoryVault #NavalWarfare #FireShipAmbush #EpicBattle"
    },
    7: {
        "title": "The Annihilation: Siam's Greatest Naval Disaster | Forgotten Battles Ep 7",
        "badge_title": "THE FLEET DESTROYED",
        "description": "Episode 7: 'After that night, the Siamese feared the Tay Son like tigers' — the total collapse of the invading armada.\n\n#HistoryVault #HistoricalBattles #CatastrophicDefeat"
    },
    8: {
        "title": "The Aftermath & Strategic Legacy of the 1785 War | Forgotten Battles Ep 8",
        "badge_title": "LESSONS OF WAR",
        "description": "Episode 8: The conclusion of the 1785 campaign and the enduring lessons on sovereignty, river warfare, and national survival.\n\n#HistoryVault #MilitaryStrategy #HistoryDocumentary"
    }
}


def get_episode_number(filename):
    match = re.search(r'ep(\d+)', filename, re.IGNORECASE)
    if match:
        return int(match.group(1))
    return 1

def main():
    video_dir = os.path.join('content', 'videos_4k')
    video_files = sorted(glob.glob(os.path.join(video_dir, "ep*_4k.mp4")))
    if not video_files:
        video_dir = os.path.join('content', 'videos')
        video_files = sorted(glob.glob(os.path.join(video_dir, "ep*.mp4")))
    if not video_files:
        video_dir = 'downloads'
        video_files = sorted(glob.glob(os.path.join(video_dir, "ep*.mp4")))
    
    thumb_dir = os.path.join('content', 'thumbnails')
    sub_base_dir = os.path.join('content', 'subtitles')
    os.makedirs(thumb_dir, exist_ok=True)
    os.makedirs(sub_base_dir, exist_ok=True)

    if not video_files:
        print("Không tìm thấy file video nào trong content/videos hoặc downloads.")
        return

    print(f"=== TÌM THẤY {len(video_files)} TẬP PHIM ĐÃ TẢI VỀ ===")
    for v in video_files:
        print(f" - {os.path.basename(v)}")

    # Trạng thái các tập đã upload
    uploaded_state_file = 'uploaded_episodes.json'
    uploaded_episodes = {}
    if os.path.exists(uploaded_state_file):
        try:
            with open(uploaded_state_file, 'r', encoding='utf-8') as f:
                uploaded_episodes = json.load(f)
        except Exception:
            pass

    # Lên lịch: Mỗi ngày 1 tập vào lúc 19:00 (Giờ vàng xem YouTube tại Việt Nam = 12:00 UTC)
    base_schedule = datetime.datetime.utcnow().replace(hour=12, minute=0, second=0, microsecond=0)
    current_schedule = base_schedule + datetime.timedelta(days=1)

    SUB_DISPLAY = {
        'en': 'English',
        'de': 'Deutsch (German)',
        'fr': 'Français (French)',
        'es': 'Español (Spanish)',
        'ja': '日本語 (Japanese)',
        'vi': 'Tiếng Việt (Vietnamese)'
    }

    for video_path in video_files:
        ep_num = get_episode_number(video_path)
        meta = EPISODE_METADATA.get(ep_num, {
            "title": f"Episode {ep_num}: Ancient Battles | Historical Documentary",
            "badge_title": f"EPISODE {ep_num:02d}",
            "description": "Epic historical documentary.\n#HistoryVault #UntoldBattles"
        })

        ep_sub_dir = os.path.join(sub_base_dir, f"ep{ep_num}")
        os.makedirs(ep_sub_dir, exist_ok=True)
        srt_en_path = os.path.join(ep_sub_dir, f"ep{ep_num}_en.srt")

        if str(ep_num) in uploaded_episodes:
            prev_info = uploaded_episodes[str(ep_num)]
            vid_id = prev_info.get('video_id')
            print(f"\n[ĐÃ UPLOAD] Tập {ep_num} (Video ID: {vid_id}). Đang kiểm tra đồng bộ phụ đề đa ngôn ngữ...")
            if os.path.exists(srt_en_path):
                sub_files = generate_multilingual_subtitles_for_ep(srt_en_path, ep_sub_dir)
                for lang_code, sub_path in sub_files.items():
                    try:
                        upload_subtitle(vid_id, sub_path, language=lang_code, name=f"{SUB_DISPLAY.get(lang_code, lang_code.upper())}")
                    except Exception as e:
                        print(f" [Lưu ý Phụ đề {lang_code}] {e}")
            # Tăng ngày lên lịch cho tập tiếp theo
            current_schedule += datetime.timedelta(days=1)
            continue

        print(f"\n==========================================")
        print(f"XỬ LÝ TẬP {ep_num}: {os.path.basename(video_path)}")
        print(f"Lên lịch phát hành: {current_schedule.strftime('%Y-%m-%d %H:%M UTC')} (19:00 Giờ VN)")
        print(f"Tiêu đề: {meta['title']}")
        print(f"==========================================")

        # 1. Tạo Thumbnail chuyên nghiệp
        thumb_path = os.path.join(thumb_dir, f"ep{ep_num}_thumb.jpg")
        if not os.path.exists(thumb_path):
            legacy_thumb = os.path.join('downloads', f"ep{ep_num}_thumb.jpg")
            if os.path.exists(legacy_thumb):
                import shutil
                shutil.copy(legacy_thumb, thumb_path)
            else:
                print("-> Đang tạo Thumbnail nghệ thuật...")
                create_episode_thumbnail(video_path, ep_num, meta["badge_title"], thumb_path)
        else:
            print(f"-> Đã có Thumbnail: {thumb_path}")

        # 2. Tạo Subtitle tiếng Anh bằng AI Whisper và dịch đa ngôn ngữ
        if not os.path.exists(srt_en_path):
            legacy_sub = os.path.join('downloads', f"ep{ep_num}_en.srt")
            if os.path.exists(legacy_sub):
                import shutil
                shutil.copy(legacy_sub, srt_en_path)
            else:
                print("-> Đang dùng AI Whisper trích xuất & dịch Subtitle tiếng Anh...")
                generate_english_subtitles(video_path, srt_en_path, model_name="tiny")
        else:
            print(f"-> Đã có Subtitle tiếng Anh: {srt_en_path}")

        # Tự động dịch sang Đức, Pháp, Tây Ban Nha, Nhật, Việt
        print("-> Đang tự động dịch phụ đề sang 5 thứ tiếng (Đức, Pháp, TBN, Nhật, Việt)...")
        sub_files = generate_multilingual_subtitles_for_ep(srt_en_path, ep_sub_dir)

        # 3. Đăng tải lên YouTube
        print("-> Đang upload video lên YouTube...")
        tags = ["History Vault", "history documentary", "untold battles", "ancient warfare", "naval battles", "military history", "Asian history", "epic history", "Rach Gam 1785"]
        video_id = upload_video(video_path, meta["title"], meta["description"], tags, current_schedule)

        if video_id:
            # Gắn thumbnail tự động
            try:
                set_thumbnail(video_id, thumb_path)
                print(f" [OK] Đã gắn Thumbnail tự động cho Tập {ep_num}!")
            except Exception as e:
                print(f" [Lưu ý Thumbnail] {e}")

            # Gắn phụ đề đa ngôn ngữ tự động
            for lang_code, sub_path in sub_files.items():
                try:
                    upload_subtitle(video_id, sub_path, language=lang_code, name=f"{SUB_DISPLAY.get(lang_code, lang_code.upper())}")
                except Exception as e:
                    print(f" [Lưu ý Phụ đề {lang_code}] {e}")

            # Lưu trạng thái
            uploaded_episodes[str(ep_num)] = {
                "video_id": video_id,
                "title": meta["title"],
                "status": "uploaded",
                "schedule": current_schedule.strftime('%Y-%m-%d %H:%M UTC')
            }
            with open(uploaded_state_file, 'w', encoding='utf-8') as f:
                json.dump(uploaded_episodes, f, indent=2, ensure_ascii=False)

        # Tăng thêm 1 ngày cho tập tiếp theo
        current_schedule += datetime.timedelta(days=1)

    print("\n🎉 TOÀN BỘ CÁC TẬP PHIM ĐÃ ĐƯỢC XỬ LÝ VÀ LÊN LỊCH PHÁT HÀNH TRÊN YOUTUBE THÀNH CÔNG!")

if __name__ == '__main__':
    main()
