#!/usr/bin/env python3
"""Make a "Giant word" video thumbnail (1920x1080 and 1080x1920): one huge pixel word with Kirupa cut out in front.

This is one of the thumbnail formats ROFL documents for Kirupa's videos (https://www.kirupa.com/design/media.htm,
"Giant word thumbnails"). The first one was the ROFL Design System video. The recipe:

- a flat, bold background with a faint 48px grid;
- one short word, usually the video's subject, in kirupaPixel (Born2bSporty v2) as wide as the canvas, filled
  kirupa orange with an 8px ink outline and a 30px stepped ink extrusion down and to the right;
- Kirupa cut out of the raw camera frame (macOS Vision person segmentation, see person_mask.swift), with a soft
  drop shadow, his head in front of one letter whose top still shows, so the word stays readable;
- a Departure Mono label in ink highlight boxes, bottom-right (top-left on the vertical);
- the official pixel orange, /pixel_icons/orange.gif, scaled 10x with nearest-neighbor;
- a few Pixel 24 KIRUPAicons tucked into corners and gaps, never over the face or the word.

First pick the frame: a natural smile with eyes on camera, from the raw camera recording, not the edited video.

    python3 scripts/giant_word_thumbnail.py --video camera.mov --sheet 30:600:15 --out-dir ~/Desktop/Video
    python3 scripts/giant_word_thumbnail.py --video camera.mov --time 187.4 --word ROFL \\
        --label "an AI-first|design system." --vertical-label "I created an|AI-first|design system." \\
        --icons robot,rolling-on-the-floor-laughing,sparkles,joystick --out-dir ~/Desktop/Video --name rofl_thumbnail

The ROFL thumbnails used the defaults: background #FAFB2B, fill #FF8000, ink #1E163C, the head over letter 1 (the
O), and the word split RO/FL on the vertical. Both files are JPEGs under YouTube's 2 MB limit and stay outside the
repository. Look at both, and at the 320x180 preview this writes, before handing them over.
"""
from __future__ import annotations

import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter, ImageFont

LIMIT = 2 * 1024 * 1024
HERE = Path(__file__).resolve().parent
# Icon slots, in order: (size, x, y). They sit in corners and gaps that stay clear of the word and the face.
WIDE_SLOTS = [(176, 1716, 655), (200, 40, 820), (96, 1790, 40), (120, 1100, 900)]
TALL_SLOTS = [(176, 870, 1450), (190, 30, 1480), (96, 940, 240), (120, 40, 1760)]


def site_root(given):
    for folder in ([Path(given)] if given else []) + [HERE, *HERE.parents]:
        if (folder / "fonts/born2bsportyv2-webfont.woff2").is_file():
            return folder
    sys.exit("Pass --site-root: the kirupaWWW checkout with fonts/, pixel_icons/, and icon/.")


def color(value):
    value = value.lstrip("#")
    if len(value) != 6:
        raise argparse.ArgumentTypeError("use a #RRGGBB color")
    return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))


def grab(video, seconds, dest):
    subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-ss", str(seconds), "-i", str(video),
                    "-frames:v", "1", str(dest)], check=True)


def contact_sheet(video, spec, dest):
    start, end, step = (float(part) for part in spec.split(":"))
    times, t = [], start
    while t <= end:
        times.append(t)
        t += step
    cells = []
    with tempfile.TemporaryDirectory() as tmp:
        for t in times:
            grab(video, t, Path(tmp) / "f.png")
            cell = Image.open(Path(tmp) / "f.png").convert("RGB")
            cell.thumbnail((480, 360))
            ImageDraw.Draw(cell).text((8, 6), f"{t:g}s", fill="yellow", stroke_width=2, stroke_fill="black")
            cells.append(cell)
    cols = 5
    w, h = max(c.width for c in cells), max(c.height for c in cells)
    sheet = Image.new("RGB", (cols * w, -(-len(cells) // cols) * h), "black")
    for i, cell in enumerate(cells):
        sheet.paste(cell, ((i % cols) * w, (i // cols) * h))
    sheet.save(dest, quality=85)
    print(dest)


def head(alpha):
    """Head top, center x, and width in a person mask: the widest row before the neck narrows."""
    solid = alpha.point(lambda v: 255 if v > 128 else 0)
    box = solid.getbbox()
    if not box:
        sys.exit("The mask has no person in it.")
    top, best = box[1], None
    for y in range(top, top + int((box[3] - top) * 0.45)):
        row = solid.crop((0, y, solid.width, y + 1)).getbbox()
        if not row:
            continue
        width = row[2] - row[0]
        if best and width < best[0] * 0.92 and y - top > best[0] * 0.3:
            break
        if not best or width > best[0]:
            best = (width, (row[0] + row[2]) / 2)
    return top, best[1], best[0]


def grid(size, light):
    layer = Image.new("RGBA", size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(layer)
    line = (0, 0, 0, 18) if light else (255, 255, 255, 16)
    for x in range(0, size[0], 48):
        draw.line([(x, 0), (x, size[1])], fill=line, width=2)
    for y in range(0, size[1], 48):
        draw.line([(0, y), (size[0], y)], fill=line, width=2)
    return layer


def fit(font_file, lines, width, height):
    """The largest font size whose widest line fits width and whose lines each fit height."""
    size = 2000
    probe = ImageDraw.Draw(Image.new("RGB", (1, 1)))
    while size > 40:
        font = ImageFont.truetype(font_file, size)
        boxes = [probe.textbbox((0, 0), line, font=font) for line in lines]
        if max(b[2] - b[0] for b in boxes) <= width and max(b[3] - b[1] for b in boxes) <= height:
            return size
        size -= 1
    sys.exit("The word is too long for this format. Use one short word.")


def giant(canvas, font, text, left, top, fill, ink, depth, stroke):
    """Draw text with its ink box's top-left at (left, top): extrusion first, then the outlined face.
    Returns each letter's ink box."""
    draw = ImageDraw.Draw(canvas)
    box = draw.textbbox((0, 0), text, font=font)
    x, y = left - box[0], top - box[1]
    for i in range(depth, 0, -1):
        draw.text((x + i, y + i), text, font=font, fill=ink)
    draw.text((x, y), text, font=font, fill=fill, stroke_width=stroke, stroke_fill=ink)
    return [draw.textbbox((x + draw.textlength(text[:i], font=font), y), ch, font=font) for i, ch in enumerate(text)]


def label(canvas, font_file, lines, size, x, y, bg, fg, pad=(18, 8), gap=12):
    font = ImageFont.truetype(font_file, size)
    draw = ImageDraw.Draw(canvas)
    for line in lines:
        box = draw.textbbox((0, 0), line, font=font)
        draw.rectangle([x, y, x + box[2] - box[0] + pad[0] * 2, y + size + pad[1] * 2], fill=bg)
        draw.text((x + pad[0] - box[0], y + pad[1] - box[1] + (size - (box[3] - box[1])) // 2), line, font=font, fill=fg)
        y += size + pad[1] * 2 + gap
    return y


def label_size(font_file, lines, size, pad=(18, 8), gap=12):
    font = ImageFont.truetype(font_file, size)
    probe = ImageDraw.Draw(Image.new("RGB", (1, 1)))
    width = max(probe.textbbox((0, 0), line, font=font)[2] - probe.textbbox((0, 0), line, font=font)[0] for line in lines)
    return width + pad[0] * 2, len(lines) * (size + pad[1] * 2 + gap) - gap


def place(canvas, person, top, cx, width, at_x, at_top, shadow):
    """Scale the cutout so the head is `width` wide, centered on at_x, its top at at_top, with a soft shadow."""
    scale = width / person[3]
    image = person[0].resize((round(person[0].width * scale), round(person[0].height * scale)), Image.LANCZOS)
    x, y = int(at_x - person[2] * scale), int(at_top - top * scale)
    alpha = image.split()[3]
    under = Image.new("RGBA", image.size, shadow + (255,))
    under.putalpha(alpha.point(lambda v: int(v * 0.6)))
    layer = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
    layer.paste(under, (x + 18, y + 12), under)
    canvas.alpha_composite(layer.filter(ImageFilter.GaussianBlur(22)))
    canvas.paste(image, (x, y), image)


def icons(canvas, root, specs, slots):
    for i, spec in enumerate(specs):
        parts = spec.split("@")
        name = parts[0]
        if len(parts) == 3:
            size, (x, y) = int(parts[1]), (int(v) for v in parts[2].split(","))
        elif i < len(slots):
            size, x, y = slots[i]
        else:
            sys.exit(f"Give {name} a size and position: {name}@SIZE@X,Y")
        path = root / "icon/pixel-twemoji-24/png-192" / f"{name}.png"
        if not path.is_file():
            sys.exit(f"No Pixel 24 KIRUPAicon named {name} in icon/pixel-twemoji-24/png-192/")
        canvas.alpha_composite(Image.open(path).convert("RGBA").resize((size, size), Image.NEAREST), (x, y))


def save(canvas, dest):
    canvas.convert("RGB").save(dest, quality=92, optimize=True)
    if dest.stat().st_size >= LIMIT:
        sys.exit(f"{dest} is over YouTube's 2 MB thumbnail limit")
    print(dest)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--video", help="the raw camera recording")
    ap.add_argument("--time", type=float, help="seconds into --video for the frame")
    ap.add_argument("--sheet", metavar="START:END:STEP", help="write a contact sheet of --video frames and stop")
    ap.add_argument("--frame", help="a still instead of --video and --time")
    ap.add_argument("--mask", help="a person mask for the frame (default: run person_mask.swift)")
    ap.add_argument("--word", help="one short word, usually the video's subject")
    ap.add_argument("--vertical-word", help="the word's two lines on the vertical, like RO/FL (default: split in half)")
    ap.add_argument("--label", default="", help="label lines separated by |")
    ap.add_argument("--vertical-label", help="label lines for the vertical (default: --label)")
    ap.add_argument("--icons", default="", help="Pixel 24 KIRUPAicon names, comma-separated, filled into the corner "
                    "slots in order; NAME@SIZE@X,Y places one exactly")
    ap.add_argument("--vertical-icons", help="the same for the vertical (default: --icons in its own slots)")
    ap.add_argument("--bg", type=color, default="#FAFB2B")
    ap.add_argument("--fill", type=color, default="#FF8000")
    ap.add_argument("--ink", type=color, default="#1E163C")
    ap.add_argument("--label-colors", metavar="BOX,TEXT", help="label box and text colors (default: ink boxes with "
                    "background-colored text on a light background, fill boxes with ink text on a dark one)")
    ap.add_argument("--head-letter", type=int, default=1, help="index of the letter the head covers (default 1)")
    ap.add_argument("--head", metavar="X,TOP,WIDTH", help="exact head center x, top, and width on the 1920x1080")
    ap.add_argument("--vertical-head", metavar="X,TOP,WIDTH", help="the same on the 1080x1920")
    ap.add_argument("--label-at", metavar="X,Y", help="the 1920x1080 label's top-left (default: bottom-right)")
    ap.add_argument("--only", choices=("wide", "tall"), help="make just one of the two")
    ap.add_argument("--site-root", help="kirupaWWW checkout (found automatically inside it)")
    ap.add_argument("--out-dir", required=True)
    ap.add_argument("--name", default="thumbnail")
    a = ap.parse_args()

    out = Path(os.path.expanduser(a.out_dir))
    out.mkdir(parents=True, exist_ok=True)
    if a.sheet:
        if not a.video:
            ap.error("--sheet needs --video")
        return contact_sheet(a.video, a.sheet, out / f"{a.name}_frames.jpg")
    if not a.word or not (a.frame or (a.video and a.time is not None)):
        ap.error("give --word and either --frame or --video with --time")
    root = site_root(a.site_root)
    pixel = str(root / "fonts/born2bsportyv2-webfont.woff2")
    mono = str(root / "ai_fundamentals/images/fonts/departure-mono.ttf")
    logo = Image.open(root / "pixel_icons/orange.gif").convert("RGBA").resize((160, 160), Image.NEAREST)
    light = sum(a.bg) > 382
    shadow = tuple(round(c * 0.32) for c in a.bg)
    box_color, text_color = ([color(v) for v in a.label_colors.split(",")] if a.label_colors else
                             (a.ink, a.bg) if light else (a.fill, a.ink))

    with tempfile.TemporaryDirectory() as tmp:
        frame = Path(a.frame) if a.frame else Path(tmp) / "frame.png"
        if not a.frame:
            grab(a.video, a.time, frame)
        mask = Path(a.mask) if a.mask else Path(tmp) / "mask.png"
        if not a.mask:
            subprocess.run(["swift", str(HERE / "person_mask.swift"), str(frame), str(mask)], check=True)
        photo = Image.open(frame).convert("RGB")
        alpha = Image.open(mask).convert("L").resize(photo.size)
    # Erode the edge a pixel and soften it, so no background halo survives.
    alpha = alpha.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(1.2))
    photo.putalpha(alpha)
    top, cx, width = head(alpha)
    person = (photo, top, cx, width)
    word = a.word

    if a.only != "tall":
        W, H = 1920, 1080
        c = Image.new("RGBA", (W, H), a.bg + (255,))
        c.alpha_composite(grid((W, H), light))
        font = ImageFont.truetype(pixel, fit(pixel, [word], W - 46, H * 0.6))
        box = ImageDraw.Draw(c).textbbox((0, 0), word, font=font)
        letters = giant(c, font, word, (W - (box[2] - box[0])) / 2, 29, a.fill, a.ink, 30, 8)
        target = letters[min(a.head_letter, len(letters) - 1)]
        x, t, w = ((float(v) for v in a.head.split(",")) if a.head else
                   ((target[0] + target[2]) / 2, target[1] + 0.34 * (target[3] - target[1]), 0.966 * (target[2] - target[0])))
        place(c, person, top, cx, w, x, t, shadow)
        lines = [line for line in a.label.split("|") if line]
        if lines:
            bw, bh = label_size(mono, lines, 72)
            lx, ly = (int(v) for v in a.label_at.split(",")) if a.label_at else (W - 20 - bw, H - 47 - bh)
            label(c, mono, lines, 72, lx, ly, box_color, text_color)
        c.alpha_composite(logo, (50, 40))
        icons(c, root, [s for s in a.icons.split(",") if s], WIDE_SLOTS)
        save(c, out / f"{a.name}_1920x1080.jpg")
        preview = c.convert("RGB").resize((320, 180), Image.LANCZOS)
        preview.save(out / f"{a.name}_preview_320x180.png")

    if a.only != "wide":
        W, H = 1080, 1920
        c = Image.new("RGBA", (W, H), a.bg + (255,))
        c.alpha_composite(grid((W, H), light))
        lines = [line for line in (a.vertical_label or a.label).split("|") if line]
        y = label(c, mono, lines, 70, 50, 40, box_color, text_color) + 11 if lines else 40
        halves = (a.vertical_word or f"{word[:(len(word) + 1) // 2]}/{word[(len(word) + 1) // 2:]}").split("/")
        font = ImageFont.truetype(pixel, fit(pixel, halves, W - 196, (H * 0.8 - y - 45) / 2))
        draw = ImageDraw.Draw(c)
        rows = []
        for half in halves:
            box = draw.textbbox((0, 0), half, font=font)
            rows.append(giant(c, font, half, (W - (box[2] - box[0])) / 2 - 15, y, a.fill, a.ink, 30, 8))
            y += box[3] - box[1] + 45
        low = rows[-1]
        left, right, ltop, lbottom = low[0][0], low[-1][2], low[0][1], low[0][3]
        x, t, w = ((float(v) for v in a.vertical_head.split(",")) if a.vertical_head else
                   ((left + right) / 2 - 19, ltop + 0.43 * (lbottom - ltop), 0.433 * W))
        place(c, person, top, cx, w, x, t, shadow)
        c.alpha_composite(logo, (W - 200, 40))
        icons(c, root, [s for s in (a.vertical_icons if a.vertical_icons is not None else a.icons).split(",") if s], TALL_SLOTS)
        save(c, out / f"{a.name}_1080x1920.jpg")


if __name__ == "__main__":
    main()
