# -*- coding: utf-8 -*-
import subprocess,os,json,sys
S="/tmp/claude-1000/-home-clawd/16492513-0f24-4b26-8e34-c28a8085f218/scratchpad/"
V="/home/clawd/uploads/curso-aws-1/Lesson2-AIB-C01-ES.mp4"
TR=S+"tramos/"; os.makedirs(TR,exist_ok=True)

# reconstruir la línea de tiempo desde concat.txt (png + duración) acumulando el inicio
lineas=open(S+"concat.txt").read().split("\n")
tr=[]; t=0.0
for i in range(0,len(lineas)-1):
    if lineas[i].startswith("file ") and i+1<len(lineas) and lineas[i+1].startswith("duration "):
        png=lineas[i][6:-1]; d=float(lineas[i+1].split()[1])
        tr.append({"png":png,"t":round(t,3),"d":d}); t+=d
print(f"{len(tr)} tramos · cubren {t:.2f}s", flush=True)

FILT=("[1:v]crop=764:1920:158:0,scale=430:1080,fps=30,setpts=PTS-STARTPTS,format=yuv420p[cam];"
      "[0:v]format=yuv420p[bg];[bg][cam]overlay=0:0:shortest=1[v]")
hechos=0
for k,e in enumerate(tr):
    out=f"{TR}t{k:03d}.mp4"
    if os.path.exists(out) and os.path.getsize(out)>2000:
        hechos+=1; continue
    cmd=["nice","-n","15","ffmpeg","-nostdin","-v","error",
         "-loop","1","-framerate","30","-t",str(e["d"]),"-i",e["png"],
         "-ss",str(e["t"]),"-t",str(e["d"]),"-i",V,
         "-filter_complex",FILT,"-map","[v]","-an",
         "-c:v","libx264","-preset","veryfast","-crf","20","-threads","2",
         "-pix_fmt","yuv420p","-g","30","-x264-params","scenecut=0",out,"-y"]
    subprocess.run(cmd,check=True)
    hechos+=1
    print(f"  tramo {k+1}/{len(tr)}  {e['d']:.1f}s  {os.path.getsize(out)/1e6:.1f} MB", flush=True)
print(f"{hechos} tramos listos", flush=True)

with open(S+"tramos.txt","w") as f:
    for k in range(len(tr)): f.write(f"file '{TR}t{k:03d}.mp4'\n")
# pegar sin recodificar y traer el audio TAL CUAL del máster
subprocess.run(["nice","-n","15","ffmpeg","-nostdin","-v","error",
                "-f","concat","-safe","0","-i",S+"tramos.txt","-i",V,
                "-map","0:v","-map","1:a","-c","copy","-movflags","+faststart",
                S+"leccion2-es-v1.mp4","-y"],check=True)
d=float(subprocess.check_output(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",S+"leccion2-es-v1.mp4"]).strip())
print(f"RENDER OK · {d:.2f}s ({int(d)//60}:{int(d)%60:02d}) · {os.path.getsize(S+'leccion2-es-v1.mp4')/1e6:.0f} MB")
