"""「次の1秒を3Dに」today の後半（Physical Intelligence の π0.5 の枚）に、PI の公式動画の窓（6-1 B）を入れる。
2026-11-29 の決まり「Physical Intelligence の話をしている所には、PI の公式動画を数秒入れる」に合わせた差し替え。
書き出した本編（orig.mp4）の該当フレームだけを、紙の上の窓＋札＋出典＋字幕＋ハコブくんに替える
窓の映像は pi.website/blog/pi05 の items in drawer（src/pi05_items_in_drawer.mp4 → src/pi_win_c.mp4）の0〜6秒。
12/7 の動画で使った紹介動画（PiV9）とは別の映像にする（2026-11-29 エイイチ「毎回同じなのはNG」）"""
import sys, os, html, json, subprocess
import numpy as np
from PIL import Image
BASE = os.path.abspath('../_制作ベース')
sys.path.insert(0, '.'); sys.path.insert(1, BASE); os.environ['P2M_BASE'] = BASE
from timing import load, layout, narration, FPS, SR
from subtitle import SUB_CX, SUB_MAXW, split_lines, pages
from scene_kit import overlay
from hakobu import Hakobu
from playwright.sync_api import sync_playwright
import importlib.util as ilu

PI_CSS = """
.fuda{position:absolute;left:140px;top:96px;display:flex;align-items:center;gap:14px;font-size:30px;font-weight:700;color:#0D0D0D}
.fuda .k{padding:6px 18px;border-radius:999px;font-size:28px;font-weight:900;background:#0D0D0D;color:#fff}
.tcr{position:absolute;left:420px;top:790px;font-size:26px;font-weight:700;color:#555}
"""
SUBCSS = """*{margin:0;padding:0}html,body{width:1920px;height:1080px;background:transparent}
svg{position:absolute;left:0;top:0}
.t{font-family:'Noto Sans CJK JP',sans-serif;font-size:52px;font-weight:800;fill:#fff;stroke:#0D0D0D;stroke-width:11px;stroke-linejoin:round;stroke-linecap:round;paint-order:stroke fill}"""

idx = load(); total = layout(idx)
o = next(x for x in idx if x['scene'] == 'today')
pk, a, b = o['parts'][1]                        # 2枚目「Physical Intelligence の π0.5 という、ロボット用の AI です。」
F0, F1 = o['start'] + a, o['start'] + b
ptxt = pages(o['text'])[pk]
print('差し替え', F0, F1, F0 / FPS, F1 / FPS, ptxt)

with sync_playwright() as p:
    br = p.chromium.launch(); pg = br.new_page(viewport={'width': 1920, 'height': 1080})
    pg.set_content(overlay(f'<style>{PI_CSS}</style><div class="fuda"><span class="k">映像の引用</span><span>Physical Intelligence の π0.5 の公開映像（引き出しに片付ける）</span></div>'
                           '<div class="tcr">映像：Physical Intelligence「π0.5: a VLA with Open-World Generalization」（pi.website/blog/pi05）</div>'))
    pg.wait_for_timeout(200); pg.screenshot(path='fix/pi_ovl.png', omit_background=True)
    lines = split_lines(ptxt)
    svg = ''.join(f'<text x="{SUB_CX}" text-anchor="middle" class="t">{html.escape(ln)}</text>' for ln in lines)
    pg.set_content(f'<!doctype html><html><head><meta charset="utf-8"><style>{SUBCSS}</style></head><body><svg width="1920" height="1080" viewBox="0 0 1920 1080">{svg}</svg></body></html>')
    pg.evaluate(f"""() => {{ const ts=[...document.querySelectorAll('text.t')]; const lh=72; const n=ts.length; let fs=52;
      for (const t of ts){{ const w=t.getComputedTextLength(); if (w>{SUB_MAXW}) fs=Math.min(fs, Math.floor(52*{SUB_MAXW}/w)); }}
      ts.forEach((t,k)=>{{ t.style.fontSize=fs+'px'; t.setAttribute('y', 1080-62-(n-1-k)*lh); }}); }}""")
    pg.screenshot(path='fix/sub.png', omit_background=True)
    br.close()

# ハコブくん：assemble.py と同じ計算で全体の動きを出し、差し替える範囲だけ使う
hk = Hakobu()
pcm = narration(idx)
sp = ilu.spec_from_file_location('_n', os.path.abspath('narration.py')); nm = ilu.module_from_spec(sp); sp.loader.exec_module(nm)
EI = list(getattr(nm, 'EI_LINES', []))
m = pcm.astype(np.float32) / 32768.0
for x in idx:
    if x['i'] in EI:
        m[int(x['start'] / FPS * SR):int((x['start'] + x['frames']) / FPS * SR)] = 0
tl = [(x['start'], x['start'] + x['frames'], x['start'] + x['speech'], x.get('face', 'base'), bool(x['text'])) for x in idx]
prm = hk.animate(tl, m)
n = F1 - F0
seg = 'fix/seg_today_pi.mp4'
cmd = ['ffmpeg', '-v', 'error', '-y', '-i', 'src/pi_win_c.mp4', '-loop', '1', '-i', 'fix/pi_ovl.png', '-loop', '1', '-i', 'fix/sub.png',
       '-f', 'rawvideo', '-pix_fmt', 'rgba', '-s', f'{hk.w}x{hk.h}', '-r', str(FPS), '-i', '-',
       '-filter_complex', f'[0:v]fps={FPS},scale=1920:1080,setsar=1[b];[b][1:v]overlay[c];[c][2:v]overlay[d];[d][3:v]overlay=x={hk.x}:y={hk.y}[v]',
       '-map', '[v]', '-frames:v', str(n), '-c:v', 'libx264', '-preset', 'medium', '-crf', '14', '-pix_fmt', 'yuv420p', '-r', str(FPS), seg]
pr = subprocess.Popen(cmd, stdin=subprocess.PIPE)
for i in range(F0, F1):
    pr.stdin.write(hk.frame(prm[i]).tobytes())
pr.stdin.close(); assert pr.wait() == 0
json.dump(dict(F0=F0, F1=F1, total=total), open('fix/range.json', 'w'))
print('ok', n)

