# -*- coding: utf-8 -*-
"""Render completo de una lección: línea de tiempo + tramos + pegado, con soporte de panel de video."""
import re,json,unicodedata,difflib,subprocess,os,sys
S="/tmp/claude-1000/-home-clawd/16492513-0f24-4b26-8e34-c28a8085f218/scratchpad/"
sys.path.insert(0,S); os.chdir(S)
from motor import parsear, render, PANEL

LEC=sys.argv[1]; SLIDES=sys.argv[2]; PALABRAS=sys.argv[3]; CAM=sys.argv[4]; PANSRC=sys.argv[5]; SAL=sys.argv[6]
TR=f"{S}tramos_{SLIDES}/"; os.makedirs(TR,exist_ok=True)
DUR=float(subprocess.check_output(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",CAM]).strip())

def norm(s):
    s=unicodedata.normalize('NFD',s.lower()); s=''.join(c for c in s if unicodedata.category(c)!='Mn')
    return re.sub(r'[^a-z0-9ñ ]',' ',s)
pal=json.load(open(PALABRAS))
toks=[norm(p["w"]).strip() for p in pal]; plano=" ".join(toks); pos=[];c=0
for tk in toks: pos.append(c); c+=len(tk)+1
def tiempo(fr,desde=0):
    n=" ".join(norm(fr).split()); i=plano.find(n,desde)
    if i<0:
        L=len(n.split()); mejor=(0,-1); ini=len(plano[:desde].split())
        for k in range(ini,len(toks)-L+1):
            r=difflib.SequenceMatcher(None,n," ".join(toks[k:k+L])).ratio()
            if r>mejor[0]: mejor=(r,k)
        if mejor[0]<0.85: return None,desde
        i=pos[mejor[1]]
    wi=max(k for k,p in enumerate(pos) if p<=i)
    return pal[wi]["t"], i+len(n)

man=render(LEC,SLIDES)
laminas,_=parsear(LEC)
linea=[]; desde=0
for li,L in enumerate(laminas):
    tE=0.0 if li==0 else tiempo(L["props"].get("entra"),desde)[0]
    assert tE is not None, f"lámina {li}: entrada sin resolver"
    ts=[tE]
    if L["props"].get("plantilla")!="portada":
        for v in L["vinetas"]:
            if not v["cue"]: continue
            t,desde=tiempo(v["cue"],desde)
            assert t is not None, f"lámina {li}: disparo «{v['cue']}» sin resolver"
            ts.append(t)
    for n,t in enumerate(ts):
        m=next(x for x in man if x["lamina"]==li and x["estado"]==n)
        linea.append({"png":m["png"],"t":t,"hueco":m["hueco"],"entra":tE})
linea.sort(key=lambda x:x["t"])
for i,e in enumerate(linea):
    e["fin"]=linea[i+1]["t"] if i+1<len(linea) else DUR
    e["d"]=round(e["fin"]-e["t"],3)
assert all(e["d"]>0 for e in linea), "estado de duración no positiva"
assert abs(sum(e["d"] for e in linea)-DUR)<0.05, "la línea de tiempo no cubre el audio"
print(f"{len(linea)} estados · {sum(e['d'] for e in linea):.2f}s de {DUR:.2f}s · mínimo {min(e['d'] for e in linea):.2f}s",flush=True)

PX,PY,PW,PH=PANEL
CAMF="crop=764:1920:158:0,scale=430:1080,fps=30,setpts=PTS-STARTPTS,format=yuv420p"
for k,e in enumerate(linea):
    out=f"{TR}t{k:03d}.mp4"
    if os.path.exists(out) and os.path.getsize(out)>2000: continue
    if e["hueco"]:
        off=e["t"]-e["entra"]
        filt=(f"[3:v]fps=30,setpts=PTS-STARTPTS,format=yuv420p[pan];[0:v]format=yuv420p[bg];"
              f"[bg][pan]overlay={PX}:{PY}:shortest=1[cp];[2:v]format=rgba[sl];"
              f"[cp][sl]overlay=0:0:shortest=1[base];[1:v]{CAMF}[cam];[base][cam]overlay=0:0:shortest=1[v]")
        cmd=["nice","-n","15","ffmpeg","-nostdin","-v","error",
             "-f","lavfi","-i",f"color=c=0xFBFBF9:s=1920x1080:r=30:d={e['d']}",
             "-ss",str(e["t"]),"-t",str(e["d"]),"-i",CAM,
             "-loop","1","-framerate","30","-t",str(e["d"]),"-i",e["png"],
             "-ss",f"{max(0,off):.3f}","-t",str(e["d"]),"-i",PANSRC,
             "-filter_complex",filt]
    else:
        filt=f"[0:v]format=yuv420p[bg];[1:v]{CAMF}[cam];[bg][cam]overlay=0:0:shortest=1[v]"
        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",CAM,
             "-filter_complex",filt]
    cmd+=["-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)
    print(f"  {k+1}/{len(linea)} · {e['d']:.1f}s · panel {'sí' if e['hueco'] else 'no'}",flush=True)

lst=f"{S}tramos_{SLIDES}.txt"
open(lst,"w").write("".join(f"file '{TR}t{k:03d}.mp4'\n" for k in range(len(linea))))
subprocess.run(["nice","-n","15","ffmpeg","-nostdin","-v","error","-f","concat","-safe","0","-i",lst,
                "-i",CAM,"-map","0:v","-map","1:a","-c","copy","-movflags","+faststart",SAL,"-y"],check=True)
d=float(subprocess.check_output(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",SAL]).strip())
print(f"RENDER OK · {SAL} · {d:.2f}s ({int(d)//60}:{int(d)%60:02d}) · {os.path.getsize(SAL)/1e6:.0f} MB")
