import os
import sys
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance

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

def generate_full_movie_thumbnail():
    src_art = "content/thumbnails/full_movie_thumb_art.jpg"
    out_1080p = "content/thumbnails/full_movie_thumb.jpg"
    out_4k = "content/thumbnails/full_movie_thumb_4k.jpg"
    out_4k_dir_jpg = "content/thumbnails_4k/full_movie_thumb_4k.jpg"
    out_4k_dir_png = "content/thumbnails_4k/full_movie_thumb_4k.png"

    if not os.path.exists(src_art):
        print(f"[-] Không tìm thấy file gốc: {src_art}")
        return

    art_img = Image.open(src_art).convert("RGBA")

    # Inpaint clean sky over original upper text
    w_p, h_p = 440, 52
    patch = art_img.crop((160, 110, 160 + w_p, 110 + h_p))
    art_img.paste(patch, (160, 32))

    img_4k = art_img.resize((3840, 2160), Image.Resampling.LANCZOS)
    overlay = Image.new("RGBA", (3840, 2160), (0, 0, 0, 0))
    d = ImageDraw.Draw(overlay)

    font_path = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts", "arialbd.ttf")
    f_title = ImageFont.truetype(font_path, 72) if os.path.exists(font_path) else ImageFont.load_default()
    f_b4k = ImageFont.truetype(font_path, 105) if os.path.exists(font_path) else ImageFont.load_default()
    f_series = ImageFont.truetype(font_path, 60) if os.path.exists(font_path) else ImageFont.load_default()

    # 1. Top Left Badge: FULL DOCUMENTARY (Imperial Red with Gold Border)
    text_tl = "FULL DOCUMENTARY"
    bbox_tl = f_title.getbbox(text_tl)
    w_tl = bbox_tl[2] - bbox_tl[0]
    box_tl = [90, 90, 90 + w_tl + 80, 90 + 170]
    d.rounded_rectangle([box_tl[0]+8, box_tl[1]+8, box_tl[2]+8, box_tl[3]+8], radius=32, fill=(0, 0, 0, 160))
    d.rounded_rectangle(box_tl, radius=32, fill=(185, 25, 25, 235), outline=(255, 215, 0, 240), width=6)
    d.text((box_tl[0] + 40, box_tl[1] + 40), text_tl, fill=(255, 255, 255, 255), font=f_title)

    # 2. Top Right Badge: 4K UHD (Obsidian Glass with Gold Border)
    margin_r = 90
    top = 90
    box_w = 560
    box_h = 170
    right = 3840 - margin_r
    left = right - box_w
    bottom = top + box_h
    d.rounded_rectangle([left+8, top+8, right+8, bottom+8], radius=32, fill=(0, 0, 0, 180))
    d.rounded_rectangle([left, top, right, bottom], radius=32, fill=(14, 14, 18, 240), outline=(255, 215, 0, 240), width=6)
    bbox_4k = f_b4k.getbbox("4K ")
    bbox_uhd = f_b4k.getbbox("UHD")
    tot_w = (bbox_4k[2] - bbox_4k[0]) + (bbox_uhd[2] - bbox_uhd[0])
    sx = left + (box_w - tot_w) // 2
    ty = top + (box_h - (bbox_4k[3] - bbox_4k[1])) // 2 - bbox_4k[1] // 2
    d.text((sx, ty), "4K ", fill=(255, 215, 0, 255), font=f_b4k)
    d.text((sx + (bbox_4k[2] - bbox_4k[0]), ty), "UHD", fill=(255, 255, 255, 255), font=f_b4k)

    # 3. Companion Badge: COMPLETE SERIES (36 MINS)
    text_series = "COMPLETE SERIES (36 MINS)"
    bbox_s = f_series.getbbox(text_series)
    w_s = bbox_s[2] - bbox_s[0]
    box_s = [left - 40 - w_s - 80, 90, left - 40, 90 + 170]
    d.rounded_rectangle([box_s[0]+8, box_s[1]+8, box_s[2]+8, box_s[3]+8], radius=32, fill=(0, 0, 0, 160))
    d.rounded_rectangle(box_s, radius=32, fill=(14, 14, 18, 240), outline=(220, 220, 220, 220), width=4)
    d.text((box_s[0] + 40, box_s[1] + 45), text_series, fill=(255, 215, 0, 255), font=f_series)

    final_4k = Image.alpha_composite(img_4k, overlay).convert("RGB")

    # Save 4K PNG and optimized 4K JPG (< 2MB)
    os.makedirs("content/thumbnails_4k", exist_ok=True)
    final_4k.save(out_4k_dir_png, "PNG")
    final_4k.save(out_4k_dir_jpg, "JPEG", quality=94, subsampling=1)
    final_4k.save(out_4k, "JPEG", quality=94, subsampling=1)
    print(f"✓ Đã xuất ảnh thumbnail 4K UHD: {out_4k} & {out_4k_dir_jpg}")

    # Downscale to 1080p (1920x1080) for standard YouTube thumbnail
    final_1080 = final_4k.resize((1920, 1080), Image.Resampling.LANCZOS)
    final_1080.save(out_1080p, "JPEG", quality=95)
    print(f"✓ Đã xuất ảnh thumbnail 1080p: {out_1080p}")

if __name__ == "__main__":
    generate_full_movie_thumbnail()
