import os
import sys
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance
import moviepy as mp

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

def create_episode_thumbnail(video_path, ep_number, title_text, output_thumb_path):
    """
    Tạo thumbnail phong cách phim tài liệu lịch sử:
    - Trích xuất frame đẹp nhất (ở khoảng 20% thời lượng)
    - Tăng độ tương phản và bão hòa màu nhẹ
    - Áp dụng gradient tối để làm nổi bật chữ
    - Chèn Badge Tập phim và Tiêu đề nổi bật
    """
    clip = mp.VideoFileClip(video_path)
    # Lấy frame ở thời điểm 15s hoặc 20% thời lượng
    target_time = min(25.0, clip.duration * 0.25)
    raw_frame_path = output_thumb_path + "_raw.png"
    clip.save_frame(raw_frame_path, t=target_time)
    clip.close()

    # Mở ảnh bằng PIL
    base_img = Image.open(raw_frame_path).convert("RGBA")
    base_img = base_img.resize((1280, 720), Image.Resampling.LANCZOS)

    # Tăng nhẹ độ nét và độ tương phản
    enhancer = ImageEnhance.Contrast(base_img)
    base_img = enhancer.enhance(1.15)

    # Tạo lớp phủ gradient bóng mờ góc dưới và bên trái
    overlay = Image.new("RGBA", (1280, 720), (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    # Vẽ dải tối ở nửa dưới ảnh để chữ dễ đọc
    for y in range(400, 720):
        alpha = int(180 * ((y - 400) / 320.0))
        draw.line([(0, y), (1280, y)], fill=(10, 10, 15, alpha))

    # Vẽ dải tối ở góc trên bên trái cho badge
    draw.rounded_rectangle([35, 35, 290, 105], radius=15, fill=(180, 20, 20, 220)) # Đỏ hoàng gia

    # Thử nạp font hệ thống hoặc dùng font mặc định
    font_badge = None
    font_title = None
    for font_name in ["arialbd.ttf", "segoeprb.ttf", "tahoma.ttf", "arial.ttf"]:
        try:
            font_path = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts", font_name)
            if os.path.exists(font_path):
                font_badge = ImageFont.truetype(font_path, 38)
                font_title = ImageFont.truetype(font_path, 52)
                break
        except Exception:
            pass

    if not font_badge:
        font_badge = ImageFont.load_default()
        font_title = ImageFont.load_default()

    # Vẽ chữ "EPISODE X" lên badge
    draw.text((55, 48), f"EPISODE {ep_number:02d}", fill=(255, 255, 255, 255), font=font_badge)

    # Hợp nhất ảnh và overlay
    final_img = Image.alpha_composite(base_img, overlay).convert("RGB")
    final_draw = ImageDraw.Draw(final_img)

    # Vẽ tiêu đề với viền bóng (Drop Shadow)
    title_x = 50
    title_y = 570
    
    # Bóng đen xung quanh
    for offset in [(-3, -3), (-3, 3), (3, -3), (3, 3), (0, 4), (4, 0)]:
        final_draw.text((title_x + offset[0], title_y + offset[1]), title_text, fill=(0, 0, 0), font=font_title)

    # Chữ vàng đồng hoàng tộc
    final_draw.text((title_x, title_y), title_text, fill=(255, 215, 0), font=font_title)

    final_img.save(output_thumb_path, quality=95)
    
    # Xoá frame tạm
    if os.path.exists(raw_frame_path):
        os.remove(raw_frame_path)

    print(f"Đã tạo thumbnail thành công: {output_thumb_path}")
    return output_thumb_path

if __name__ == '__main__':
    create_episode_thumbnail('downloads/ep1.mp4', 1, "PRINCE IN EXILE", "downloads/ep1_thumb.jpg")
