# How-to clip "วิธีกรอกใบสมัคร รอบ 3": animated phone walkthrough built from real form screenshots + "ใกล้แค่เอื้อม" from bar 15.441
# usage: make.py stills t1,t2,...   |   make.py full [vo.mp3]
import asyncio, json, os, subprocess, sys
from playwright.async_api import async_playwright
W = '/home/claude/promo/howto'; FPS = 25
P = json.load(open(W + '/plan.json')); L = P['L']; S0 = P['S0']
SH = ['01_verify', '02_verify_phone', '03_otp_box', '04_otp_filled', '05_wait', '07_form', '08_code', '09_nick', '11_plaque', '12_phone', '13_tiktok', '15_done']
A = {s: f'shots/{s}.png' for s in SH}; A['logo'] = '/home/claude/review/mg/logo.png'
D = {'boxes': json.load(open(f'{W}/shots/boxes.json')), 'sc': P['sc']}
mode = sys.argv[1]
async def frames(times, sink):
    async with async_playwright() as p:
        b = await p.chromium.launch(); pg = await b.new_page(viewport={'width': 720, 'height': 1280}, device_scale_factor=1.5)
        await pg.goto('file://' + W + '/howto.html'); await pg.evaluate('([a,d])=>setup(a,d)', [A, D]); await pg.evaluate('document.fonts.ready.then(()=>1)')
        for t in times:
            await pg.evaluate('t=>render(t)', t); await sink(t, await pg.screenshot())
        await b.close()
if mode == 'stills':
    ts = [float(x) for x in sys.argv[2].split(',')]; os.makedirs(f'{W}/stills', exist_ok=True)
    async def sv(t, png): open(f'{W}/stills/t{t:06.2f}.png', 'wb').write(png)
    asyncio.run(frames(ts, sv))
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-pattern_type', 'glob', '-i', f'{W}/stills/t*.png', '-vf', 'scale=270:480,tile=%dx1' % len(ts), '-frames:v', '1', f'{W}/stills_sheet.png'], check=True)
    for f in os.listdir(f'{W}/stills'): os.remove(f'{W}/stills/' + f)
    print('sheet ok')
    sys.exit()
def mix(VO):
    # band-split ducking under the voice (low/mid/high 0.30/0.55/0.35) so the voice is clear and the singer is still heard
    import numpy as np, scipy.signal as ss
    from scipy.io import wavfile
    SR = 48000; n = int(L * SR)
    def load(pth, extra=()):
        subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', pth, *extra, '-ac', '2', '-ar', str(SR), '-f', 'wav', f'{W}/tmp.wav'], check=True)
        return wavfile.read(f'{W}/tmp.wav')[1].astype(np.float32) / 32768
    song = load('/home/claude/promo/song3/s3.m4a', ['-ss', f'{S0:.3f}', '-t', str(L + 1), '-af', 'loudnorm=I=-15:TP=-2:LRA=11'])
    M = np.zeros((n, 2), np.float32); M[:min(n, len(song))] = song[:n]; V = np.zeros((n, 2), np.float32)
    if VO:
        vo = load(VO, ['-af', 'highpass=f=90,acompressor=threshold=0.08:ratio=3:attack=5:release=90:makeup=2,loudnorm=I=-15:TP=-2:LRA=7'])
        for a, b, at in P['vo']:
            seg = vo[int(a * SR):int(b * SR)].copy(); f = int(0.03 * SR); seg[:f] *= np.linspace(0, 1, f)[:, None]; seg[-f:] *= np.linspace(1, 0, f)[:, None]
            i = int(at * SR); m = min(len(seg), n - i); V[i:i + m] += seg[:m]
    env = np.sqrt(np.convolve(V[:, 0] ** 2, np.ones(int(0.05 * SR)) / (0.05 * SR), 'same'))
    k = int(0.5 * SR); sp = np.convolve((env > 0.01).astype(np.float32), np.ones(k) / k, 'same'); mask = np.clip(sp * 2.5, 0, 1)
    t = np.arange(n) / SR; g = np.clip(t / 0.15, 0, 1); fo = t > L - 0.8; g[fo] *= (1 - (t[fo] - (L - 0.8)) / 0.8) ** 1.5
    lo = ss.sosfiltfilt(ss.butter(4, 250, 'low', fs=SR, output='sos'), M, axis=0); hi = ss.sosfiltfilt(ss.butter(4, 5000, 'high', fs=SR, output='sos'), M, axis=0); mid = M - lo - hi
    M = (lo * (g * (1 - 0.30 * mask))[:, None] + mid * (g * (1 - 0.55 * mask))[:, None] + hi * (g * (1 - 0.35 * mask))[:, None]).astype(np.float32)
    mx = V * 1.35 + M * 0.95; mx /= max(1, np.abs(mx).max() / 0.97)
    wavfile.write(f'{W}/mix_raw.wav', SR, (np.clip(mx, -1, 1) * 32767).astype(np.int16))
if mode == 'mix':
    mix(sys.argv[2] if len(sys.argv) > 2 else None); print('mix ok'); sys.exit()
else:
    VO = sys.argv[2] if len(sys.argv) > 2 else None
    n = int(round(L * FPS))
    ff = subprocess.Popen(['ffmpeg', '-v', 'error', '-y', '-f', 'image2pipe', '-framerate', '25', '-c:v', 'png', '-i', '-', '-frames:v', str(n),
                           '-c:v', 'libx264', '-preset', 'medium', '-crf', '15', '-pix_fmt', 'yuv420p', '-r', '25', f'{W}/film.mp4'], stdin=subprocess.PIPE)
    async def wr(t, png): ff.stdin.write(png)
    asyncio.run(frames([i / FPS for i in range(n)], wr)); ff.stdin.close(); ff.wait()
    mix(VO)
    out = f'{W}/howto_r3_' + ('vo' if VO else 'music') + '.mp4'
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', f'{W}/film.mp4', '-i', f'{W}/mix_raw.wav', '-map', '0:v', '-map', '1:a', '-c:v', 'copy',
                    '-af', 'alimiter=limit=0.89,loudnorm=I=-14:TP=-1.5:LRA=9', '-ar', '48000', '-c:a', 'aac', '-b:a', '192k', '-t', str(L), '-movflags', '+faststart', out], check=True)
    print('done', out)
