"""
add_4k_badge.py - Batch adds premium '4K UHD' badges to all 4K thumbnails
for the 1785 Historical Naval War Documentary Series.

Updates:
  - content/thumbnails_4k/ (3840x2160 PNG lossless + JPG < 2MB YouTube compliant)
  - content/thumbnails/ (1080p/720p synced versions for YouTube Studio Extension)
"""

import os
import sys
import glob
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import numpy as np

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

PROJECT_DIR = Path(__file__).resolve().parent
THUMBS_DIR = PROJECT_DIR / "content" / "thumbnails"
THUMBS_4K_DIR = PROJECT_DIR / "content" / "thumbnails_4k"

THUMBS_DIR.mkdir(parents=True, exist_ok=True)
THUMBS_4K_DIR.mkdir(parents=True, exist_ok=True)

FONT_PATH = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts", "arialbd.ttf")

def get_font(size: int):
    if os.path.exists(FONT_PATH):
        try:
            return ImageFont.truetype(FONT_PATH, size)
        except Exception:
            pass
    return ImageFont.load_default()

def save_optimized_jpg(pil_img: Image.Image, out_path: Path, max_mb: float = 1.95):
    """Saves JPEG ensuring file size is strictly under max_mb (YouTube 2MB limit)."""
    for q in [94, 92, 90, 88, 85, 80]:
        pil_img.save(str(out_path), "JPEG", quality=q, subsampling=1)
        sz_mb = out_path.stat().st_size / (1024 * 1024)
        if sz_mb <= max_mb:
            return sz_mb, q
    return sz_mb, q

def render_episode_4k_badge(base_img: Image.Image) -> Image.Image:
    """Renders the Obsidian + Gold 4K UHD badge in the top-right corner of a 3840x2160 thumbnail."""
    w, h = base_img.size # 3840, 2160
    overlay = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    d = ImageDraw.Draw(overlay)

    font_badge = get_font(105)

    margin_r = 137
    top = 105
    box_w = 560
    box_h = 212
    right = w - margin_r
    left = right - box_w
    bottom = top + box_h

    # 1. Subtle drop shadow for depth
    d.rounded_rectangle([left + 8, top + 8, right + 8, bottom + 8], radius=32, fill=(0, 0, 0, 180))

    # 2. Sleek Obsidian Glass Capsule with Golden Imperial Border
    d.rounded_rectangle([left, top, right, bottom], radius=32, fill=(14, 14, 18, 240), outline=(255, 215, 0, 240), width=6)

    # 3. High-contrast typography: Gold '4K ' + Pure White 'UHD'
    bbox_4k = font_badge.getbbox("4K ")
    bbox_uhd = font_badge.getbbox("UHD")
    w_4k = bbox_4k[2] - bbox_4k[0]
    w_uhd = bbox_uhd[2] - bbox_uhd[0]
    total_w = w_4k + w_uhd

    start_x = left + (box_w - total_w) // 2
    ty = top + (box_h - (bbox_4k[3] - bbox_4k[1])) // 2 - bbox_4k[1] // 2

    d.text((start_x, ty), "4K ", fill=(255, 215, 0, 255), font=font_badge)
    d.text((start_x + w_4k, ty), "UHD", fill=(255, 255, 255, 255), font=font_badge)

    return Image.alpha_composite(base_img.convert("RGBA"), overlay)

def render_ep1_thumbnail(base_img: Image.Image) -> Image.Image:
    """Renders the English EPISODE 01 badge, PRINCE IN EXILE title with gold accent, and 4K UHD badge onto EP1."""
    w, h = 3840, 2160
    overlay = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    d = ImageDraw.Draw(overlay)
    f_badge = get_font(105)
    f_title = get_font(160)
    f_b4k = get_font(105)

    # 1. Top-Left Badge: EPISODE 01 (Imperial Red)
    box_badge = [105, 105, 872, 317]
    d.rounded_rectangle([box_badge[0] + 8, box_badge[1] + 8, box_badge[2] + 8, box_badge[3] + 8], radius=32, fill=(0, 0, 0, 180))
    d.rounded_rectangle(box_badge, radius=32, fill=(185, 25, 25, 240), outline=(220, 20, 20, 255), width=2)
    bbox_text = f_badge.getbbox("EPISODE 01")
    tw = bbox_text[2] - bbox_text[0]
    th = bbox_text[3] - bbox_text[1]
    tx = box_badge[0] + (box_badge[2] - box_badge[0] - tw) // 2
    ty = box_badge[1] + (box_badge[3] - box_badge[1] - th) // 2 - bbox_text[1] // 2
    d.text((tx, ty), "EPISODE 01", fill=(255, 255, 255, 255), font=f_badge)

    # 2. Top-Right Badge: 4K UHD (Obsidian Glass + Gold Border)
    margin_r = 137
    top = 105
    box_w = 560
    box_h = 212
    right = w - 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")
    w_4k = bbox_4k[2] - bbox_4k[0]
    w_uhd = bbox_uhd[2] - bbox_uhd[0]
    total_w = w_4k + w_uhd
    start_x = left + (box_w - total_w) // 2
    ty_4k = top + (box_h - (bbox_4k[3] - bbox_4k[1])) // 2 - bbox_4k[1] // 2
    d.text((start_x, ty_4k), "4K ", fill=(255, 215, 0, 255), font=f_b4k)
    d.text((start_x + w_4k, ty_4k), "UHD", fill=(255, 255, 255, 255), font=f_b4k)

    # 3. Bottom Title Banner: PRINCE IN EXILE
    d.rectangle([0, 1745, 3840, 2035], fill=(0, 0, 0, 255))
    d.line([(0, 1745), (3840, 1745)], fill=(255, 215, 0, 220), width=6)

    title_text = "PRINCE IN EXILE"
    title_x = 160
    bbox_title = f_title.getbbox(title_text)
    tit_h = bbox_title[3] - bbox_title[1]
    title_y = 1745 + (290 - tit_h) // 2 - bbox_title[1] // 2

    for ox, oy in [(-3, -3), (3, 3), (-3, 3), (3, -3), (0, 4), (4, 0)]:
        d.text((title_x + ox, title_y + oy), title_text, fill=(20, 20, 20, 255), font=f_title)
    d.text((title_x, title_y), title_text, fill=(255, 215, 0, 255), font=f_title)

    return Image.alpha_composite(base_img.convert("RGBA"), overlay)

def generate_full_movie_thumbnails():
    """Generates pristine 4K UHD and 1080p thumbnails for Full Movie Omnibus."""
    src_art = THUMBS_DIR / "full_movie_thumb_art.jpg"
    if not src_art.exists():
        print(f"[-] Không tìm thấy artwork Full Movie: {src_art}")
        return

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

    # Inpaint / clean the original text 'HISTORICAL CONFLICTS' in upper sky
    w_p, h_p = 440, 52
    patch = art_img.crop((160, 110, 160 + w_p, 110 + h_p))
    art_img.paste(patch, (160, 32))

    # Render at 4K (3840x2160)
    img_4k = art_img.resize((3840, 2160), Image.Resampling.LANCZOS)
    overlay = Image.new("RGBA", (3840, 2160), (0, 0, 0, 0))
    d = ImageDraw.Draw(overlay)

    f_title = get_font(72)
    f_b4k = get_font(105)
    f_series = get_font(60)

    # 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 lossless & 4K JPG
    out_4k_png = THUMBS_4K_DIR / "full_movie_thumb_4k.png"
    out_4k_jpg = THUMBS_4K_DIR / "full_movie_thumb_4k.jpg"
    out_4k_content_jpg = THUMBS_DIR / "full_movie_thumb_4k.jpg"

    final_4k.save(str(out_4k_png), "PNG")
    sz_mb, q = save_optimized_jpg(final_4k, out_4k_jpg)
    save_optimized_jpg(final_4k, out_4k_content_jpg)
    print(f"  ✓ Full Movie 4K saved: {out_4k_jpg.name} ({sz_mb:.2f}MB, Q={q}) & PNG")

    # Downscale to 1080p (1920x1080) for standard YouTube thumbnail
    final_1080 = final_4k.resize((1920, 1080), Image.Resampling.LANCZOS)
    out_1080_jpg = THUMBS_DIR / "full_movie_thumb.jpg"
    final_1080.save(str(out_1080_jpg), "JPEG", quality=95)
    print(f"  ✓ Full Movie 1080p saved: {out_1080_jpg.name} ({out_1080_jpg.stat().st_size / 1024:.1f}KB)")

def process_all_thumbnails():
    print("=" * 70)
    print(" BATCH ADDING '4K UHD' BADGE TO ALL THUMBNAILS")
    print(f" Source 4K: {THUMBS_4K_DIR}")
    print(f" Output 1080p/720p: {THUMBS_DIR}")
    print("=" * 70)

    # 1. Episodes 1 to 8
    print("\n[1/2] Processing Episodes 1 to 8 (3840x2160 UHD)...")
    for i in range(1, 9):
        # Look for lossless PNG first, fallback to JPG
        src_png = THUMBS_4K_DIR / f"ep{i}_thumb_4k.png"
        src_jpg = THUMBS_4K_DIR / f"ep{i}_thumb_4k.jpg"
        
        src_file = src_png if src_png.exists() else src_jpg
        if not src_file.exists():
            print(f"  [-] Không tìm thấy file 4K cho EP{i}")
            continue

        base_img = Image.open(src_file)
        if base_img.size != (3840, 2160):
            base_img = base_img.resize((3840, 2160), Image.Resampling.LANCZOS)

        # Render 4K badges & titles (EP1 uses English EPISODE 01 + PRINCE IN EXILE)
        if i == 1:
            badged_4k = render_ep1_thumbnail(base_img)
        else:
            badged_4k = render_episode_4k_badge(base_img)

        # Save 4K lossless PNG
        badged_4k.save(str(src_png), "PNG")

        # Save 4K JPG (< 2MB)
        sz_mb, q = save_optimized_jpg(badged_4k.convert("RGB"), src_jpg)
        print(f"  ✓ EP{i}: 4K PNG + JPG saved ({sz_mb:.2f}MB, Q={q})")

        # Downscale to standard 1280x720 thumbnail in content/thumbnails/
        tgt_res = (1280, 720)
        downscaled = badged_4k.resize(tgt_res, Image.Resampling.LANCZOS).convert("RGB")
        out_thumb_jpg = THUMBS_DIR / f"ep{i}_thumb.jpg"
        downscaled.save(str(out_thumb_jpg), "JPEG", quality=95)
        print(f"      -> Synced 720p thumbnail: {out_thumb_jpg.name} ({out_thumb_jpg.stat().st_size / 1024:.1f}KB)")

    # 2. Full Movie Omnibus
    print("\n[2/2] Processing Full Movie Cinema Omnibus (3840x2160 UHD)...")
    generate_full_movie_thumbnails()

    print("\n" + "=" * 70)
    print("🎉 HOÀN TẤT GẮN NHÃN 4K UHD VÀ ĐỒNG BỘ TOÀN BỘ THUMBNAIL THÀNH CÔNG!")
    print("=" * 70)

if __name__ == "__main__":
    process_all_thumbnails()
