"""感情型のショート（2026-11-24）を、話ごとの台本 spec から組む。マンガショート_mkshort.py（第79話の型）の写しを、全画面の形に直したもの。
変えた所（2026-11-24 アナリティクスの分析: 8割が最初の1秒で次へ送っていた）
  ・最初の場面はハコブくんの顔のアップ（emo.py で 1080x1920 に描いた寄りの絵）。感情が1コマ目から見える
  ・画面いっぱいに使う: マンガのコマは横幅いっぱい（1080x1350）、上下はコマをぼかして広げた絵で埋める（ベージュの余白なし）
  ・見出しは問いにして、最初から最後まで上に出しておく
  ・まとめの画面（教訓）とサイトへの場面は入れない（サイトは概要欄と固定コメント）。最後はハコブくんの寄りで終わり、そのまま頭に戻る
使い方: python3 mkshort_emo.py spec.py [--still 秒,秒]
spec に書くもの: NAME, EP, HEAD（見出し2行・【】でオレンジ）, PANELS（コマの画像のパス P1..P4）, SCENES
  dict(kind="cu", video=mp4, lines=[...], se=[...], words=[...], zoom=1.12, dx=-90, dur=秒（省略で動画の長さ）)
  dict(kind="panel", img="P1", lines=[...], se=[...], words=[...], slam=dict(text, at, y), min=秒)
  lines: dict(v=声, who="hk"|"ns", sub="字幕", at=秒（cu のときだけ）, cut=(a,b), db=0, gap=秒)
"""
import os, sys, math, subprocess, importlib.util, functools
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageFilter

W, H, FPS, SR = 1080, 1920, 30, 48000
INK = (13, 13, 13); ORANGE = (196, 71, 31); BLUE = (120, 200, 255); SUB_OR = (255, 140, 90); YEL = (255, 214, 64)
COL = {"ink": INK, "orange": ORANGE, "white": (255, 255, 255), "yellow": YEL}
FONT = "/usr/share/fonts/opentype/noto/NotoSansCJK-Black.ttc"
F = lambda size: ImageFont.truetype(FONT, size, index=0)
HEAD_Y = 66                    # 見出しの1行目の上
SUB_Y = 1488                   # 字幕（右下のボタンと下の題名の帯より上。今までの型と同じ）
PANEL_Y = 330                  # コマを置く上端（見出しの下）
HERE = os.path.dirname(os.path.abspath(__file__))

spec_path = sys.argv[1]
sp = importlib.util.spec_from_file_location("spec", spec_path); S = importlib.util.module_from_spec(sp); sp.loader.exec_module(S)
os.chdir(os.path.dirname(os.path.abspath(spec_path)))
POP = S.POP

def load_audio(path, af=None):
    r = subprocess.run(["ffmpeg", "-v", "error", "-i", path] + (["-af", af] if af else []) + ["-f", "f32le", "-ac", "1", "-ar", str(SR), "-"], capture_output=True)
    return np.frombuffer(r.stdout, np.float32).copy()
TEMPO = 1.12        # 声を少しだけ速く（間延びすると次へ送られる。高さは変えない）
def voice(l):
    af = f"atempo={TEMPO}" + (",highpass=f=450,lowpass=f=3200" if l.get("phone") else "")
    a = load_audio(l["v"], af)
    if l.get("cut"):
        a0, a1 = (v / TEMPO if v else v for v in l["cut"]); a = a[int(a0 * SR):int(a1 * SR)] if a1 else a[int(a0 * SR):]
    e = np.abs(a); idx = np.where(e > e.max() * 0.06)[0]
    return a[max(0, idx[0] - int(0.02 * SR)):idx[-1] + int(0.08 * SR)]
def vdur(path):
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True)
    return float(r.stdout.strip())

def add_sub(st, length, l, end=None):
    pages = l["sub"].split("||")
    n = [max(1, len(p.replace("|", "").replace("【", "").replace("】", ""))) for p in pages]
    tot, acc = sum(n), 0
    for k, (pg, c) in enumerate(zip(pages, n)):
        a = st + length * acc / tot; acc += c
        SUBS.append((a, (end if k == len(pages) - 1 else st + length * acc / tot), pg, l["who"], l.get("small")))

# ---------------- 時刻を決める ----------------
T = 0.0; EVENTS = []; AUDIO = []; SUBS = []
for sc in S.SCENES:
    t0 = T
    if sc["kind"] == "cu":
        dur = sc.get("dur") or vdur(sc["video"])
        for l in sc.get("lines", []):
            a = voice(l); AUDIO.append((t0 + l["at"], a, l.get("db", 0)))
            add_sub(t0 + l["at"], len(a) / SR, l, min(t0 + l["at"] + len(a) / SR + 0.4, t0 + dur))
    else:
        cur = t0 + sc.get("lead", 0.12)
        for l in sc.get("lines", []):
            a = voice(l); st = cur + l.get("gap", 0)
            AUDIO.append((st, a, l.get("db", 0)))
            add_sub(st, len(a) / SR, l, None)
            cur = st + len(a) / SR + l.get("after", 0.22)
        dur = max(sc.get("min", 1.4), cur - t0 + sc.get("tail", 0.2))
        AUDIO.append((t0, load_audio(POP), -15))
    for se in sc.get("se", []):
        AUDIO.append((t0 + se["at"], load_audio(se["f"]), se.get("db", -6)))
    EVENTS.append((t0, t0 + dur, sc)); T += dur
TOTAL = T
SUBS.sort(key=lambda s: s[0]); fixed = []
for i, (a, b, txt, who, sm) in enumerate(SUBS):
    end_scene = next(e1 for e0, e1, _ in EVENTS if e0 <= a < e1)
    nxt = SUBS[i + 1][0] if i + 1 < len(SUBS) else TOTAL
    fixed.append((a, min(end_scene, nxt) if b is None else min(b, nxt), txt, who, sm))
SUBS = fixed

# ---------------- 部品 ----------------
def text_img(txt, size, fill=(255, 255, 255), stroke=0, stroke_fill=INK, hl=ORANGE):
    f = F(size); plain = txt.replace("【", "").replace("】", "")
    w = int(f.getlength(plain)) + stroke * 2 + 4; h = int(size * 1.32) + stroke * 2
    im = Image.new("RGBA", (w, h), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    x, on = stroke + 2, False
    for ch in txt:
        if ch in "【】": on = ch == "【"; continue
        d.text((x, stroke), ch, font=f, fill=(hl if on else fill), stroke_width=stroke, stroke_fill=stroke_fill); x += f.getlength(ch)
    return im
def paste_c(base, im, cx, cy, scale=1.0, rot=0.0):
    if scale <= 0.001: return
    if scale != 1.0: im = im.resize((max(1, int(im.width * scale)), max(1, int(im.height * scale))), Image.BILINEAR)
    if rot: im = im.rotate(rot, resample=Image.BICUBIC, expand=True)
    base.alpha_composite(im, (int(cx - im.width / 2), int(cy - im.height / 2)))
def ease(u): u = min(max(u, 0), 1); return u * u * (3 - 2 * u)
def pop(t, t0, dur=0.18):
    if t < t0: return 0
    u = (t - t0) / dur
    return 1.0 if u >= 1 else ease(u) * 1.12 if u < 0.7 else 1.12 - 0.12 * (u - 0.7) / 0.3
def slam(t, t0, dur=0.14, big=2.6):
    if t < t0: return 0
    u = (t - t0) / dur
    return 1.0 if u >= 1 else big - (big - 1) * ease(u)
def shake(t, t0, amp, dec=9, hz=23):
    if t < t0: return 0
    v = t - t0; return amp * math.exp(-v * dec) * math.sin(2 * math.pi * hz * v)

# 見出し（2行・画面の上に最後まで出しておく）
HEAD_IMG = []
for k, line in enumerate(S.HEAD):
    sz = S.HEAD_SIZE if hasattr(S, "HEAD_SIZE") else 78
    im = text_img(line, sz, fill=(255, 255, 255), stroke=12, stroke_fill=INK, hl=YEL)
    if im.width > 1020: im = im.resize((1020, int(im.height * 1020 / im.width)), Image.LANCZOS)
    HEAD_IMG.append(im)
# 見出しの下の帯（コマに寄ったときも見出しが吹き出しの字と混ざらないように、上から暗くする）
_g = np.clip(1 - (np.arange(H) - 250) / 110, 0, 1)[:, None] * 0.72
BAND = Image.fromarray(np.dstack([np.full((H, W), 18, np.uint8)] * 3 + [(np.repeat(_g, W, 1) * 255).astype(np.uint8)]), "RGBA")
CREDIT = text_img(f"4コママンガ『ハコブくん』第{S.EP}話より（つくり話・絵は生成AIで作成）", 24, fill=(255, 255, 255), stroke=3, stroke_fill=(40, 40, 40))

@functools.lru_cache(maxsize=None)
def panel_layers(path):
    """コマ（横幅いっぱい）と、上下を埋めるぼかした背景"""
    p = Image.open(path).convert("RGB")
    p = p.resize((W, int(p.height * W / p.width)), Image.LANCZOS)
    k = H / p.height * 1.08
    b = p.resize((int(p.width * k), int(p.height * k)), Image.BILINEAR)
    b = b.crop(((b.width - W) // 2, (b.height - H) // 2, (b.width - W) // 2 + W, (b.height - H) // 2 + H))
    b = b.filter(ImageFilter.GaussianBlur(28))
    b = Image.blend(b, Image.new("RGB", (W, H), (30, 30, 34)), 0.45)
    return p.convert("RGBA"), b.convert("RGBA")
_vid = {}
def vframe(path, t, zoom=1.0, dx=0, dy=0):
    if path not in _vid:
        r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True)
        _vid[path] = np.frombuffer(r.stdout, np.uint8).reshape(-1, H, W, 3)
    v = _vid[path]; i = min(max(int(round(t * FPS)), 0), len(v) - 1)
    im = Image.fromarray(v[i])
    if zoom != 1.0 or dx or dy:
        cw, ch = W / zoom, H / zoom
        x0 = (W - cw) / 2 - dx / zoom; y0 = (H - ch) / 2 - dy / zoom
        x0 = min(max(x0, 0), W - cw); y0 = min(max(y0, 0), H - ch)
        im = im.crop((int(x0), int(y0), int(x0 + cw), int(y0 + ch))).resize((W, H), Image.LANCZOS)
    return im.convert("RGBA")
_wc = {}
def word(w):
    k = (w["text"], w.get("size", 150), w.get("color", "ink"))
    if k not in _wc:
        fill = COL[w.get("color", "ink")]
        _wc[k] = text_img(w["text"], w.get("size", 150), fill=fill, stroke=14, stroke_fill=(255, 255, 255) if fill == INK else INK)
    return _wc[k]
@functools.lru_cache(maxsize=None)
def subtitle(txt, who, small):
    hl = (255, 255, 255) if who == "hk" else SUB_OR
    fill = BLUE if who == "hk" else (255, 255, 255)
    rows = txt.split("|"); plain = lambda r: len(r.replace("【", "").replace("】", ""))
    if len(rows) == 1 and plain(txt) > 13:
        cands = [i + 1 for i, ch in enumerate(txt[:-1]) if ch in "、。！？"]
        if cands:
            k = min(cands, key=lambda i: abs(plain(txt[:i]) - plain(txt) / 2)); rows = [txt[:k], txt[k:]]
    ims = [text_img(r, 70, fill=fill, stroke=12, stroke_fill=INK, hl=hl) for r in rows]
    if len(ims) == 1: return ims[0]
    out = Image.new("RGBA", (max(i.width for i in ims), sum(i.height - 14 for i in ims) + 14), (0, 0, 0, 0))
    y = 0
    for i in ims: out.alpha_composite(i, ((out.width - i.width) // 2, y)); y += i.height - 14
    return out

def frame(t):
    t0, t1, sc = next(((a, b, s) for a, b, s in EVENTS if a <= t < b), EVENTS[-1])
    lt = t - t0; u = lt / max(1e-6, t1 - t0); cam = (0, 0)
    if sc["kind"] == "cu":
        img = vframe(sc["video"], lt + sc.get("src_t0", 0), sc.get("zoom", 1.0), sc.get("dx", 0), sc.get("dy", 0))
    else:
        p, b = panel_layers(S.PANELS[sc["img"]])
        img = b.copy()
        s = 1.0 + 0.035 * ease(u) + (0.06 * (1 - ease(lt / 0.16)))      # 入りは少し大きく → すっと収まる・ゆっくり寄る
        if sc.get("focus"):                                              # コマの一部へ寄る（x, y はコマの座標・k は倍率）
            fx, fy, fk = sc["focus"]; s *= 1 + (fk - 1) * ease((lt - 0.2) / 0.6)
            cx = W / 2 + (W / 2 - fx) * (s - 1); cy = PANEL_Y + 675 + (675 - fy) * (s - 1)
        else:
            cx, cy = W / 2, PANEL_Y + 675
        paste_c(img, p, cx, cy, scale=s)
        if sc.get("slam"):
            sl = sc["slam"]
            if "_img" not in sl: sl["_img"] = word(dict(text=sl["text"], size=sl.get("size", 170), color=sl.get("color", "ink")))
            k = slam(lt, sl["at"])
            if k: paste_c(img, sl["_img"], W / 2, sl.get("y", 700), scale=k, rot=sl.get("rot", -4))
            cam = (shake(lt, sl["at"] + 0.14, 16), shake(lt, sl["at"] + 0.14, 10, 9, 29))
        img.alpha_composite(CREDIT, (W - CREDIT.width - 24, PANEL_Y + 1350 + 6))
    for w in sc.get("words", []):
        if w["at"] <= lt < w.get("until", 99):
            paste_c(img, word(w), w["x"], w["y"], scale=pop(lt, w["at"], 0.12) or 0.01, rot=w.get("rot", 0))
    if cam != (0, 0):
        img = img.transform(img.size, Image.AFFINE, (1, 0, -cam[0], 0, 1, -cam[1]), resample=Image.BILINEAR, fillcolor=(30, 30, 34, 255))
    # 見出し（最初の0.15秒で叩きつけ）
    img.alpha_composite(BAND)
    y = HEAD_Y
    for k, him in enumerate(HEAD_IMG):
        paste_c(img, him, W / 2, y + him.height / 2)          # 1コマ目から見出しが全部読めるように、動かさずに置く
        y += him.height - 18
    for a, b, txt, who, sm in SUBS:
        if a <= t < b:
            st = subtitle(txt, who, sm)
            paste_c(img, st, W / 2, SUB_Y + 60 + max(0, (st.height - 105) // 2), scale=min(pop(t, a, 0.12) or 0.01, 1.06))
    return img.convert("RGB")

if __name__ == "__main__":
    print("場面:", [(round(a, 2), round(b, 2), s["kind"]) for a, b, s in EVENTS], "合計", round(TOTAL, 1), "秒")
    if "--still" in sys.argv:
        for s in sys.argv[sys.argv.index("--still") + 1].split(","):
            frame(float(s)).save(f"still_{S.NAME}_{s}.png")
        sys.exit(0)
    n = int(TOTAL * FPS)
    p = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}", "-r", str(FPS),
                          "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20", f"video_{S.NAME}.mp4"], stdin=subprocess.PIPE)
    for i in range(n): p.stdin.write(np.asarray(frame(i / FPS)).tobytes())
    p.stdin.close(); p.wait()
    out = np.zeros(int((TOTAL + 1) * SR), np.float32)
    for t, a, db in AUDIO:
        i = int(t * SR); m = min(len(a), len(out) - i); out[i:i + m] += a[:m] * (10 ** (db / 20))
    pk = np.abs(out).max() or 1
    if pk > 0.95: out *= 0.95 / pk
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(SR), "-ac", "1", "-i", "-", f"mix_{S.NAME}.wav"], input=out.tobytes())
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", f"video_{S.NAME}.mp4", "-i", f"mix_{S.NAME}.wav", "-c:v", "copy", "-c:a", "aac",
                    "-b:a", "192k", "-af", "loudnorm=I=-16:TP=-1.5:LRA=11", "-t", f"{TOTAL:.2f}", f"out_{S.NAME}.mp4"])
    print("できあがり:", f"out_{S.NAME}.mp4", round(TOTAL, 1), "秒")
