#!/usr/bin/env python3
"""
render_v2.py - Video 2 Meta App Review: whatsapp_business_messaging
Pipeline: escala 1900x1072 -> 1920x1080 (pad preto), sem audio, 5 legendas confirmadas.

MAPEAMENTO DE GATILHOS (verificados frame a frame):
  L1: 17.0 - 30.0s   Tela Turmas visivel (f0005=20s, clique em Turmas em ~15s)
  L2: 57.0 - 68.0s   Seletor de template aberto (f0013=60s, abertura ~59s)
  L3: 90.5 - 103.0s  Clique em Disparar (zone_L4_006=93s, botao Disparar clicado)
                      Money legend - 2 linhas + zoom 1.3x no botao
  L4: FLAG - tela Mensagens com message_id NAO ENCONTRADA no screencast
             L4 omitida do render, reportada a Mia
  L5: 103.0 - 121.0s Mensagem chegou no WhatsApp Web (zone_L5_002=104s)
  L6: 147.0 - 155.16s KPIs 1-1 lidas (zone_end_024=149s, refresh mostra 1 lida)

INPUT:  1900x1072, 30fps, H264+AAC, 155.16s, 160MB
OUTPUT: 1920x1080, 30fps, H264, sem audio, ~155s
"""

import subprocess
import os
import sys
import json

INPUT = '/opt/mia/workspace/clientes/self/meta_app_review_video2/screencast_bruto.mp4'
WORK_DIR = '/opt/mia/workspace/clientes/self/meta_app_review_video2/renders'
OUTPUT = '/opt/mia/workspace/clientes/self/meta_app_review_video2/self-whatsapp_business_messaging.mp4'
FONT = '/home/mia/.fonts/px3lab/Inter-Bold.ttf'

os.makedirs(WORK_DIR, exist_ok=True)

def run(cmd, desc):
    print(f"\n=== {desc} ===", flush=True)
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"STDOUT: {result.stdout[-500:]}", flush=True)
        print(f"STDERR: {result.stderr[-2000:]}", flush=True)
        sys.exit(1)
    if result.stderr:
        lines = [l for l in result.stderr.split('\n') if l.strip()]
        if lines:
            print(f"  -> {lines[-1]}", flush=True)
    print(f"OK - {desc}", flush=True)
    return result

def ffprobe_duration(path):
    r = subprocess.run(
        ['ffprobe', '-v', 'quiet', '-show_format', '-of', 'json', path],
        capture_output=True, text=True
    )
    try:
        return float(json.loads(r.stdout)['format']['duration'])
    except:
        return 0

# ============================================================
# PASSO 1: Escalar video inteiro para 1920x1080
# Fonte: 1900x1072 -> pad para 1920x1080 (mesmo racional do video 1)
# ============================================================
nozoom_out = f'{WORK_DIR}/nozoom_base.mp4'

run([
    'ffmpeg', '-y',
    '-i', INPUT,
    '-vf', 'scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2:color=black',
    '-r', '30',
    '-c:v', 'libx264', '-crf', '17', '-preset', 'fast',
    '-an',
    nozoom_out
], 'Passo 1: Escala video completo 1920x1080 sem zoom')

d = ffprobe_duration(nozoom_out)
print(f"Base sem zoom: {d:.2f}s (esperado ~155.16s)")

# ============================================================
# PASSO 2: Queimar legendas
#
# POSICOES Y (herdadas do video 1, calibradas para 1080p):
#   safe area: barra end Y=50-80 topo, taskbar Win Y=~800 rodape
#   Zona segura pra legenda: y=805 em diante
#
#   single line: y=840
#   double line: linha1=805, linha2=870
#
# FONT SIZE: 46 (mesmo do video 1)
# ============================================================

FS = 46         # font size - mesmo do video 1
TC = 'white'
BC = '0x000000@0.87'
BP = 20         # box padding

YS  = 840   # single line
YD1 = 805   # double line, linha 1
YD2 = 870   # double line, linha 2

# L3 MONEY LEGEND - zoom 1.3x no texto (mesmo tratamento do video 1)
# Usando fontsize maior para simular zoom na legenda critica
FS_MONEY = int(FS * 1.3)  # 59px para a money legend

def dt(text, t0, t1, y, fs=None):
    """Gera filtro drawtext."""
    if fs is None:
        fs = FS
    esc = text.replace("'", "\\'").replace(':', '\\:').replace('%', '\\%')
    return (
        f"drawtext=fontfile='{FONT}'"
        f":text='{esc}'"
        f":fontcolor={TC}:fontsize={fs}"
        f":box=1:boxcolor={BC}:boxborderw={BP}"
        f":x=(w-text_w)/2:y={y}"
        f":enable='between(t,{t0},{t1})'"
    )

# L3 com zoom 1.3x: 2 linhas, font maior
# "Our app uses whatsapp_business_messaging to send messages through the Cloud API."
# Linha 1: "Our app uses whatsapp_business_messaging"
# Linha 2: "to send messages through the Cloud API."
# Posicoes Y ajustadas pra money legend maior:
YM1 = 798   # money line 1 (um pouco acima pra acomodar font maior)
YM2 = 865   # money line 2

filters = ','.join([
    # L1 - single - "Our clients import and manage their graduating students in the platform."
    dt('Our clients import and manage their graduating students in the platform.', 17.0, 30.0, YS),

    # L2 - single - "Marketing and utility messages are sent only through approved templates."
    dt('Marketing and utility messages are sent only through approved templates.', 57.0, 68.0, YS),

    # L3 - double + zoom 1.3x - MONEY LEGEND (whatsapp_business_messaging)
    # "Our app uses whatsapp_business_messaging to send messages through the Cloud API."
    dt('Our app uses whatsapp_business_messaging', 90.5, 103.0, YM1, FS_MONEY),
    dt('to send messages through the Cloud API.', 90.5, 103.0, YM2, FS_MONEY),

    # L4 OMITIDA - tela Mensagens com message_id nao encontrada no screencast
    # FLAG reportado a Mia

    # L5 - single - "The message is delivered to the recipient."
    dt('The message is delivered to the recipient.', 103.0, 121.0, YS),

    # L6 - single - "Delivery and read receipts arrive by webhook and update the dashboard."
    dt('Delivery and read receipts arrive by webhook and update the dashboard.', 147.0, 155.16, YS),
])

run([
    'ffmpeg', '-y',
    '-i', nozoom_out,
    '-vf', filters,
    '-c:v', 'libx264', '-crf', '18', '-preset', 'fast',
    '-profile:v', 'high', '-level', '4.1',
    '-an',
    '-movflags', '+faststart',
    OUTPUT
], 'Passo 2: Legendas queimadas')

# ============================================================
# VALIDACAO FINAL
# ============================================================
print("\n=== VALIDACAO FINAL ===", flush=True)
r = subprocess.run(
    ['ffprobe', '-v', 'quiet', '-show_streams', '-show_format', '-of', 'json', OUTPUT],
    capture_output=True, text=True
)
data = json.loads(r.stdout)
fmt = data['format']
streams = data['streams']

print(f"Arquivo: {OUTPUT}")
print(f"Duracao: {float(fmt['duration']):.2f}s (esperado ~155.16s)")
print(f"Tamanho: {int(fmt['size']) // 1024 // 1024}MB")
print(f"Streams: {len(streams)}")
for s in streams:
    if s['codec_type'] == 'video':
        print(f"  Video: {s['codec_name']} {s['width']}x{s['height']} {s.get('r_frame_rate','?')}fps")
    else:
        print(f"  Audio: {s['codec_name']} (ERRO - deve ser removido!)")

if len(streams) == 1 and streams[0]['codec_type'] == 'video':
    w = streams[0]['width']
    h = streams[0]['height']
    if w == 1920 and h == 1080:
        print("\nOK: 1920x1080, sem audio, H.264")
    else:
        print(f"\nAVISO: resolucao {w}x{h} (esperado 1920x1080)")
else:
    print("\nERRO: streams incorretos!")
