import os
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageEnhance

PROJECT_DIR = Path(__file__).resolve().parent
THUMBS_4K_DIR = PROJECT_DIR / "content" / "thumbnails_4k"
THUMBS_DIR = PROJECT_DIR / "content" / "thumbnails"
THUMBS_4K_DIR.mkdir(parents=True, exist_ok=True)
THUMBS_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):
    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_ep4_clean():
    src_frame = PROJECT_DIR / "downloads" / "ep4_cand_120s.jpg"
    base = Image.open(src_frame).convert("RGBA")
    w, h = base.size # 3840, 2160
    
    # Slight contrast enhancement
    enhancer = ImageEnhance.Contrast(base)
    base = enhancer.enhance(1.08)

    overlay = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    d = ImageDraw.Draw(overlay)

    # 1. Gradient darkening at bottom for title readability
    for y in range(1500, 2160):
        alpha = int(220 * ((y - 1500) / 660.0))
        d.line([(0, y), (w, y)], fill=(8, 8, 12, alpha))

    # 2. Top-Left Badge: EPISODE 04
    f_badge = get_font(85)
    text_badge = "EPISODE 04"
    bbox_b = f_badge.getbbox(text_badge)
    bw = bbox_b[2] - bbox_b[0]
    bh = bbox_b[3] - bbox_b[1]
    box_tl = [105, 105, 105 + bw + 100, 105 + bh + 80]
    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] + 50, box_tl[1] + 35), text_badge, fill=(255, 255, 255, 255), font=f_badge)

    # 3. Top-Right Badge: 4K UHD
    f_b4k = 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
    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)

    # 4. Bottom Title: THE COUNTERATTACK
    f_title = get_font(150)
    title_text = "THE COUNTERATTACK"
    tx = 120
    ty = 1820
    # Outer drop shadow for extreme contrast
    for ox in range(-6, 7, 2):
        for oy in range(-6, 7, 2):
            if ox != 0 or oy != 0:
                d.text((tx + ox, ty + oy), title_text, fill=(0, 0, 0, 255), font=f_title)
    d.text((tx, ty), title_text, fill=(255, 215, 0, 255), font=f_title)

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

    # Save 4K PNG lossless
    png_path = THUMBS_4K_DIR / "ep4_thumb_4k.png"
    final_4k.save(str(png_path), "PNG")
    print(f"Saved PNG 4K: {png_path} ({png_path.stat().st_size / (1024*1024):.2f} MB)")

    # Save 4K JPG under 2MB YouTube limit
    jpg_path = THUMBS_4K_DIR / "ep4_thumb_4k.jpg"
    sz, q = save_optimized_jpg(final_4k, jpg_path, max_mb=1.90)
    print(f"Saved JPG 4K: {jpg_path} ({sz:.2f} MB, quality={q})")

    # Downscale for 1080p sync
    thumb_1080p = final_4k.resize((1920, 1080), Image.Resampling.LANCZOS)
    sync_path = THUMBS_DIR / "ep4_thumb.jpg"
    thumb_1080p.save(str(sync_path), "JPEG", quality=90)
    print(f"Saved 1080p synced: {sync_path}")

if __name__ == "__main__":
    render_ep4_clean()
