#!/usr/bin/env python3
"""把講師圖去背並做出 3 個「說話」姿勢(輕微放大/上移,模擬隨聲音晃動)。
用法:python3 -I tools/avatar-prep.py <講師圖> <輸出資料夾> [高度px,預設 400]
輸出:<輸出資料夾>/state0.png(靜止)、state1.png(小動)、state2.png(大動),尺寸相同、透明背景、底部對齊。
去背方式:有透明通道就直接用;否則從四邊向內填滿「接近白色」的背景(不會吃掉人物內部的白色花朵)。
"""
import sys
from PIL import Image, ImageDraw, ImageFilter

src, outdir = sys.argv[1], sys.argv[2]
H = int(sys.argv[3]) if len(sys.argv) > 3 else 400

im = Image.open(src).convert('RGBA')
a = im.getchannel('A')
if a.getextrema()[0] >= 250:  # 沒有透明資訊:從邊緣填滿白底
    rgb = im.convert('RGB')
    mark = (255, 0, 255)
    w, h = rgb.size
    for xy in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2)]:
        px = rgb.getpixel(xy)
        if min(px) >= 235:  # 起點本身要是白色才填
            ImageDraw.floodfill(rgb, xy, mark, thresh=28)
    alpha = Image.new('L', im.size, 255)
    mpx, apx = rgb.load(), alpha.load()
    for y in range(h):
        for x in range(w):
            if mpx[x, y] == mark:
                apx[x, y] = 0
    # 邊緣內縮 1px 並羽化,去掉白色光暈
    alpha = alpha.filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(1.2))
    im.putalpha(alpha)

bbox = im.getchannel('A').point(lambda v: 255 if v > 16 else 0).getbbox()
im = im.crop(bbox)
scale = H / im.height
im = im.resize((max(1, round(im.width * scale)), H), Image.LANCZOS)

# 畫布留出放大與上移的空間
pad_top, pad_side = 18, 14
CW, CH = im.width + pad_side * 2, H + pad_top
for n, (k, dy) in enumerate([(1.0, 0), (1.015, 3), (1.03, 7)]):
    layer = im.resize((round(im.width * k), round(im.height * k)), Image.LANCZOS)
    canvas = Image.new('RGBA', (CW, CH), (0, 0, 0, 0))
    canvas.paste(layer, ((CW - layer.width) // 2, CH - layer.height - dy), layer)
    canvas.save(f'{outdir}/state{n}.png')
print(f'{CW}x{CH}')
