#!/usr/bin/env python3
"""
Pipeline de render para self-whatsapp_business_management.mp4
Video de App Review Meta - whatsapp_business_management permission
"""

import subprocess
import os
import sys

INPUT = '/opt/mia/workspace/videos/meta_self_tech_provider/Gravando 2026-09-02 121803.mp4'
WORK_DIR = '/opt/mia/workspace/videos/meta_self_tech_provider/renders'
OUTPUT = '/opt/mia/workspace/videos/meta_self_tech_provider/self-whatsapp_business_management.mp4'

os.makedirs(WORK_DIR, exist_ok=True)

def run(cmd, desc):
    print(f"\n=== {desc} ===")
    print(' '.join(cmd))
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"ERRO: {result.stderr[-2000:]}")
        sys.exit(1)
    print(f"OK - {desc}")
    return result

# ============================================================
# PASS 1: Renderizar segmentos de video com zoom
# Timings (em segundos no video original):
#   0-27s   : sem zoom (login + painel + abertura aba WhatsApp)
#   27-28s  : ramp in de zoom (0.5s de transicao)
#   28-82s  : zoom 1.3x (formulario + RASCUNHO + SUBMETIDO)
#   82-83s  : ramp out de zoom (0.5s de transicao)
#   83-102.5s: sem zoom (WhatsApp Manager)
#
# Crop para zoom 1.3x:
#   viewport_w = 1920/1.3 = 1477 (arredondado para par: 1476)
#   viewport_h = 1080/1.3 = 831 (arredondado para impar? nao, par: 830)
#   x_offset = 443 (centrado no formulario da direita)
#   y_offset = 0
# ============================================================

# Parametros de crop para zoom 1.3x
CROP_W = 1476  # deve ser par para x264
CROP_H = 830   # deve ser par
CROP_X = 443
CROP_Y = 0

# Segmento 1: 0 a 27s - sem zoom
seg1 = os.path.join(WORK_DIR, 'seg1.mp4')
run([
    'ffmpeg', '-y',
    '-i', INPUT,
    '-t', '27',
    '-vf', 'scale=1920:1080',
    '-r', '30', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', '-an',
    seg1
], 'Segmento 1 (0-27s sem zoom)')

# Segmento ramp_in: 27 a 28s - zoom crescendo de 1.0 para 1.3
# Usando zoompan: z sobe +0.02/frame (0.3/15 frames = 2s para chegar em 1.3 com 15 frames)
# Com +0.02/frame: 0.3/0.02 = 15 frames = 0.5s de ramp
seg_ramp_in = os.path.join(WORK_DIR, 'seg_ramp_in.mp4')
run([
    'ffmpeg', '-y',
    '-ss', '27', '-t', '1',
    '-i', INPUT,
    '-vf', (
        f'scale=1920:1080,'
        f'zoompan=z=\'min(zoom+0.02,1.3)\':'
        f'x=\'1477*(zoom-1)\':'
        f'y=0:d=30:s=1920x1080:fps=30'
    ),
    '-r', '30', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', '-an',
    seg_ramp_in
], 'Segmento ramp in (27-28s)')

# Segmento zoom: 28 a 82s - zoom fixo 1.3x via crop
seg_zoom = os.path.join(WORK_DIR, 'seg_zoom.mp4')
run([
    'ffmpeg', '-y',
    '-ss', '28', '-t', '54',
    '-i', INPUT,
    '-vf', f'scale=1920:1080,crop={CROP_W}:{CROP_H}:{CROP_X}:{CROP_Y},scale=1920:1080',
    '-r', '30', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', '-an',
    seg_zoom
], 'Segmento zoom fixo (28-82s)')

# Segmento ramp_out: 82 a 83s - zoom descendo de 1.3 para 1.0
# Para ramp out com zoompan: precisamos comecar com zoom=1.3
# Estrategia: usar zoompan com z que começa em 1.3 e decresce
# Nao tem como "iniciar" o zoompan em zoom=1.3 diretamente
# Alternativa: usar blend entre frame com crop e frame normal
#
# Implementacao: usar blend filter
# blend=all_expr='A*(1-T/N)+B*(T/N)' onde T=frame_index, N=total_frames
# A = frame com crop (zoomed), B = frame normal
seg_ramp_out = os.path.join(WORK_DIR, 'seg_ramp_out.mp4')
run([
    'ffmpeg', '-y',
    '-ss', '82', '-t', '1',
    '-i', INPUT,
    '-ss', '82', '-t', '1',
    '-i', INPUT,
    '-filter_complex', (
        f'[0:v]scale=1920:1080,crop={CROP_W}:{CROP_H}:{CROP_X}:{CROP_Y},scale=1920:1080[zoomed];'
        f'[1:v]scale=1920:1080[normal];'
        f'[zoomed][normal]blend=all_expr=\'A*(1-T/{30})+B*(T/{30})\'[out]'
    ),
    '-map', '[out]',
    '-r', '30', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', '-an',
    seg_ramp_out
], 'Segmento ramp out (82-83s blend)')

# Segmento 3: 83s ao fim - sem zoom
seg3 = os.path.join(WORK_DIR, 'seg3.mp4')
run([
    'ffmpeg', '-y',
    '-ss', '83',
    '-i', INPUT,
    '-vf', 'scale=1920:1080',
    '-r', '30', '-c:v', 'libx264', '-crf', '18', '-preset', 'fast', '-an',
    seg3
], 'Segmento 3 (83s-fim sem zoom)')

# ============================================================
# CONCAT dos segmentos
# ============================================================
concat_list = os.path.join(WORK_DIR, 'concat.txt')
with open(concat_list, 'w') as f:
    for seg in [seg1, seg_ramp_in, seg_zoom, seg_ramp_out, seg3]:
        f.write(f"file '{seg}'\n")

concat_out = os.path.join(WORK_DIR, 'concat_out.mp4')
run([
    'ffmpeg', '-y',
    '-f', 'concat', '-safe', '0',
    '-i', concat_list,
    '-c', 'copy',
    concat_out
], 'Concatenar segmentos')

# Verificar duracao do concat
result = subprocess.run(
    ['ffprobe', '-v', 'quiet', '-show_format', '-of', 'json', concat_out],
    capture_output=True, text=True
)
print(f"Concat duration: {result.stdout[:500]}")

# ============================================================
# PASS 2: Adicionar legendas com drawtext
# Legendas:
#   1: 0-17s   "This is Self, our platform for graduation companies in Brazil."
#   2: 22-27s  "Our clients manage their WhatsApp message templates here."
#   3: 28-46s  (2 linhas) "Our app uses whatsapp_business_management to create message" / "templates on behalf of our clients."
#   4: 46-63s  "Variables are filled per student, so each message is personalized."
#   5: 76-82s  (2 linhas) "The template is submitted to Meta through the API, and our platform" / "reads the approval status so it only sends what Meta approved."
#   6: 82-102s "The same template, now visible in WhatsApp Manager."
#
# NOTA: apos o concat, os timings sao os mesmos do video original
# porque nao cortamos nada (apenas zoom diferente em segmentos)
#
# Estilo das legendas:
# - Posicao: y=880 (terco inferior, sem cobrir formulario)
# - Fundo: retangulo preto opacity 0.85
# - Texto: branco, DM Sans Bold, tamanho 42
# - Entra/sai seco (enable por range de tempo)
# ============================================================

# Verificar fontes disponiveis
result = subprocess.run(['fc-list', ':lang=en'], capture_output=True, text=True)
fonts = result.stdout

# Preferencia: DM Sans > Space Grotesk > Barlow Condensed > Liberation Sans
font_path = None
for font_name in ['Inter', 'DM Sans', 'SpaceGrotesk', 'Barlow', 'Liberation Sans', 'DejaVu Sans']:
    if font_name.lower().replace(' ', '') in fonts.lower().replace(' ', '').replace('-', ''):
        # Extrair path preferindo Bold
        for line in fonts.split('\n'):
            if font_name.lower() in line.lower() and 'bold' in line.lower():
                font_path = line.split(':')[0].strip()
                break
        if not font_path:
            for line in fonts.split('\n'):
                if font_name.lower() in line.lower():
                    font_path = line.split(':')[0].strip()
                    break
    if font_path:
        break

if not font_path:
    # Usar Inter Bold (premium instalada) como fallback
    inter_bold = '/home/mia/.fonts/px3lab/Inter-Bold.ttf'
    if os.path.exists(inter_bold):
        font_path = inter_bold
    else:
        font_path = '/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf'

print(f"Fonte selecionada: {font_path}")

# Configuracoes das legendas
FONT_SIZE = 46
TEXT_COLOR = 'white'
BOX_COLOR = '0x000000@0.87'  # preto opacity 87%
BOX_BORDER = 20  # padding interno do box
# Posicao validada: legenda no terco inferior sem cobrir conteudo do formulario
# Single line: y=940 (centro da area de legenda)
# Double line: linha1 = y=920, linha2 = y=978
Y_SINGLE = 940
Y_DOUBLE_LINE1 = 920
Y_DOUBLE_LINE2 = 978

def drawtext_filter(text, start, end, font, size, y, color, box_color, box_border):
    """Gera expressao drawtext do ffmpeg."""
    # Escapar aspas e dois pontos no texto
    text_esc = text.replace("'", "\\'").replace(':', '\\:')
    enable = f'between(t,{start},{end})'
    return (
        f"drawtext=fontfile='{font}'"
        f":text='{text_esc}'"
        f":fontcolor={color}"
        f":fontsize={size}"
        f":box=1:boxcolor={box_color}:boxborderw={box_border}"
        f":x=(w-text_w)/2"
        f":y={y}"
        f":enable='{enable}'"
    )

# Construir filtro de legendas
# Legenda 1: linha unica
l1 = drawtext_filter(
    'This is Self, our platform for graduation companies in Brazil.',
    0, 17, font_path, FONT_SIZE, Y_SINGLE, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Legenda 2: linha unica
l2 = drawtext_filter(
    'Our clients manage their WhatsApp message templates here.',
    22, 27, font_path, FONT_SIZE, Y_SINGLE, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Legenda 3: 2 linhas (linha1 + linha2 juntas)
# Linha 1 da legenda 3
l3a = drawtext_filter(
    'Our app uses whatsapp_business_management to create message',
    28, 46, font_path, FONT_SIZE, Y_DOUBLE_LINE1, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)
# Linha 2 da legenda 3
l3b = drawtext_filter(
    'templates on behalf of our clients.',
    28, 46, font_path, FONT_SIZE, Y_DOUBLE_LINE2, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Legenda 4: linha unica
l4 = drawtext_filter(
    'Variables are filled per student, so each message is personalized.',
    46, 63, font_path, FONT_SIZE, Y_SINGLE, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Legenda 5: 2 linhas - a mais critica
l5a = drawtext_filter(
    'The template is submitted to Meta through the API, and our platform',
    76, 82, font_path, FONT_SIZE, Y_DOUBLE_LINE1, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)
l5b = drawtext_filter(
    'reads the approval status so it only sends what Meta approved.',
    76, 82, font_path, FONT_SIZE, Y_DOUBLE_LINE2, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Legenda 6: linha unica (WhatsApp Manager)
l6 = drawtext_filter(
    'The same template, now visible in WhatsApp Manager.',
    82, 102.5, font_path, FONT_SIZE, Y_SINGLE, TEXT_COLOR, BOX_COLOR, BOX_BORDER
)

# Juntar todos os filtros em cadeia
vf = ','.join([l1, l2, l3a, l3b, l4, l5a, l5b, l6])

run([
    'ffmpeg', '-y',
    '-i', concat_out,
    '-vf', vf,
    '-c:v', 'libx264', '-crf', '18', '-preset', 'fast',
    '-profile:v', 'high', '-level', '4.0',
    '-an',
    '-movflags', '+faststart',
    OUTPUT
], 'Pass 2: adicionar legendas')

print(f"\n=== RENDER COMPLETO ===")
print(f"Output: {OUTPUT}")

# Validar com ffprobe
result = subprocess.run(
    ['ffprobe', '-v', 'quiet', '-show_streams', '-show_format', '-of', 'json', OUTPUT],
    capture_output=True, text=True
)
print(f"ffprobe: {result.stdout[:1500]}")
