# -*- coding: utf-8 -*-
import re,json,unicodedata,difflib,subprocess,os,sys
S="/tmp/claude-1000/-home-clawd/16492513-0f24-4b26-8e34-c28a8085f218/scratchpad/"
LEC="/home/clawd/playgrounds/curso-aibc01/lecciones/leccion-02.md"
VID="/home/clawd/uploads/curso-aws-1/Lesson2-AIB-C01-ES.mp4"
SAL=sys.argv[1] if len(sys.argv)>1 else S+"leccion2-es-v1.mp4"
DUR=float(subprocess.check_output(["ffprobe","-v","error","-show_entries","format=duration","-of","csv=p=0",VID]).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(S+"l2es_palabras.json"))
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)

sys.path.insert(0,S); from motor import parsear
laminas,_=parsear(LEC)

linea=[]; desde=0
for li,L in enumerate(laminas):
    ent=L["props"].get("entra")
    tE,desde=(0.0,desde) if li==0 else tiempo(ent,desde) if ent else (None,desde)
    assert tE is not None, f"lámina {li}: no resuelve su entrada «{ent}»"
    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 sin resolver «{v['cue']}»"
            ts.append(t)
    for n,t in enumerate(ts):
        linea.append({"png":f"{S}l2/l{li:02d}_s{n:02d}.png","t":t})

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["dur"]=round(e["fin"]-e["t"],3)
assert all(e["dur"]>0 for e in linea), "hay estados de duración cero o negativa"
assert abs(sum(e["dur"] for e in linea)-DUR)<0.05, "la línea de tiempo no cubre el audio"
print(f"{len(linea)} estados · cobertura {sum(e['dur'] for e in linea):.2f}s de {DUR:.2f}s · mínimo {min(e['dur'] for e in linea):.2f}s")

with open(S+"concat.txt","w") as f:
    for e in linea:
        f.write(f"file '{e['png']}'\nduration {e['dur']}\n")
    f.write(f"file '{linea[-1]['png']}'\n")

cmd=["ffmpeg","-nostdin","-v","error","-stats",
     "-f","concat","-safe","0","-i",S+"concat.txt",
     "-i",VID,
     "-filter_complex",
     "[0:v]fps=30,format=yuv420p[bg];"
     "[1:v]crop=764:1920:158:0,scale=430:1080,fps=30,format=yuv420p[cam];"
     "[bg][cam]overlay=0:0:shortest=1[v]",
     "-map","[v]","-map","1:a","-c:v","libx264","-preset","medium","-crf","19",
     "-c:a","aac","-b:a","192k","-movflags","+faststart","-t",str(DUR),SAL,"-y"]
print(" ".join(cmd[:6]),"…")
subprocess.run(cmd,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")
