#!/usr/bin/env python3
"""
render3.py - Video sem zoom (pedido do Renato em 2026-09-02)
Pipeline simplificado: escala direto 1920x1080, sem crop, sem zoompan.
"""

import subprocess
import os
import sys
import json

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'
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[-1500:]}", 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 sem zoom
# Fonte: 1902x1068 - pad para 1920x1080
# ============================================================
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
], 'Escala video completo 1920x1080 sem zoom')

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

# ============================================================
# PASSO 2: Queimar legendas
#
# TIMINGS (baseados nos gatilhos visuais, mesmos do render anterior):
#   L1: 0.0  - 17.0s  login + painel carregando
#   L2: 22.0 - 27.0s  aba WhatsApp aberta
#   L3: 28.0 - 46.0s  preenchimento formulario (2 linhas, SEM zoom)
#   L4: 46.0 - 63.0s  corpo + variaveis + exemplos (SEM zoom)
#   --: 63.0 - 76.0s  sem legenda (RASCUNHO -> SUBMETIDO)
#   L5: 76.0 - 82.0s  SUBMETIDO na lista (2 linhas, minimo 5s, SEM zoom)
#   L6: 82.0 - 102.5s WhatsApp Manager
#
# POSICOES Y (calibradas para 1080p sem zoom):
#   - Barra de enderecos: y=50-80px (topo, nao cobrir)
#   - Conteudo critico termina em ~y=750px (formulario inteiro visivel)
#   - Barra de tarefas Windows: y=760-800px (rodape)
#   - Zona segura pra legenda: y=805px em diante
#
#   single line: y=840 (linha unica centralizada verticalmente na faixa)
#   double line: linha1=805, linha2=870 (duas linhas com espacamento adequado)
# ============================================================

FS = 46         # font size
TC = 'white'
BC = '0x000000@0.87'
BP = 20         # box padding

# Posicoes Y calibradas para sem zoom
YS  = 840   # single line
YD1 = 805   # double line, linha 1
YD2 = 870   # double line, linha 2

def dt(text, t0, t1, y):
    """Gera filtro drawtext."""
    esc = text.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})'"
    )

filters = ','.join([
    # L1 - single
    dt('This is Self, our platform for graduation companies in Brazil.', 0, 17, YS),
    # L2 - single
    dt('Our clients manage their WhatsApp message templates here.', 22, 27, YS),
    # L3 - double (sem zoom)
    dt('Our app uses whatsapp_business_management to create message', 28, 46, YD1),
    dt('templates on behalf of our clients.', 28, 46, YD2),
    # L4 - single (sem zoom)
    dt('Variables are filled per student, so each message is personalized.', 46, 63, YS),
    # L5 - double (sem zoom) - minimo 6s garantido (76-82s = 6s)
    dt('The template is submitted to Meta through the API, and our platform', 76, 82, YD1),
    dt('reads the approval status so it only sends what Meta approved.', 76, 82, YD2),
    # L6 - single
    dt('The same template, now visible in WhatsApp Manager.', 82, 102.5, 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
], 'Pass 2: legendas queimadas (sem zoom)')

# ============================================================
# 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 ~102.5s)")
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!")
