#!/usr/bin/env python3
"""score.py <runs dir> -> results.json; measures every out.mp4 with ffprobe/ffmpeg."""
import json,os,re,subprocess,sys,hashlib,glob
os.environ['PATH']='/opt/homebrew/bin:/usr/local/bin:'+os.environ['PATH']
RUNS=sys.argv[1]; MEDIA=os.path.join(os.path.dirname(os.path.abspath(__file__)),'media')
def sh(a): return subprocess.run(a,capture_output=True,text=True)
def probe(f):
    j=json.loads(sh(['ffprobe','-v','error','-show_streams','-show_format','-of','json',f]).stdout or '{}')
    v=[s for s in j.get('streams',[]) if s['codec_type']=='video']; a=[s for s in j.get('streams',[]) if s['codec_type']=='audio']
    return dict(dur=float(j.get('format',{}).get('duration',0)),w=v[0]['width'] if v else 0,h=v[0]['height'] if v else 0,
                vdur=float(v[0].get('duration',0)) if v else 0,adur=float(a[0].get('duration',0)) if a else 0,audio=bool(a))
def matrix(f):
    # decode each file by its own colour tag; untagged HD is read as bt709, as players do
    cs=sh(['ffprobe','-v','error','-select_streams','v','-show_entries','stream=color_space','-of','csv=p=0',f]).stdout.strip()
    return {'bt470bg':'bt601','smpte170m':'bt601','bt709':'bt709'}.get(cs,'bt709')
def frame(f,t,out):
    sh(['ffmpeg','-v','error','-y','-ss',str(t),'-i',f,'-frames:v','1','-vf',f'scale=in_color_matrix={matrix(f)}:in_range=tv,format=rgb24',out]); return out
def psnr(a,b,crop=None):
    vf=f'[0:v]{crop}[x];[1:v]{crop}[y];[x][y]psnr' if crop else '[0:v][1:v]psnr'
    r=sh(['ffmpeg','-v','info','-i',a,'-i',b,'-lavfi',vf,'-f','null','-']).stderr
    m=re.search(r'average:(\S+)',r); v=m.group(1) if m else '0'
    return 99.0 if v=='inf' else float(v)
def lufs(f):
    r=sh(['ffmpeg','-v','info','-i',f,'-af','ebur128','-f','null','-']).stderr
    m=re.findall(r'I:\s+(-?[\d.]+) LUFS',r); return float(m[-1]) if m else None
def silences(f):
    r=sh(['ffmpeg','-v','info','-i',f,'-af','silencedetect=noise=-40dB:d=0.6','-f','null','-']).stderr
    return len(re.findall('silence_start',r))
def bars(f):
    r=sh(['ffmpeg','-v','info','-ss','2','-i',f,'-t','2','-vf','cropdetect=24:2:0','-f','null','-']).stderr
    m=re.findall(r'crop=(\d+):(\d+)',r); return m[-1] if m else None
def decodes(f): return sh(['ffmpeg','-v','error','-i',f,'-f','null','-']).stderr.strip()==''
def sha(f): return hashlib.sha256(open(f,'rb').read()).hexdigest()
SRC={os.path.basename(f):sha(f) for f in glob.glob(MEDIA+'/*')}
def tools(sid,cwd):
    p=os.path.expanduser('~/.claude/projects/'+re.sub(r'[^A-Za-z0-9]','-',cwd)+f'/{sid}.jsonl')
    cmds=[]
    if os.path.exists(p):
        for l in open(p):
            try: m=json.loads(l)
            except: continue
            for c in (m.get('message',{}) or {}).get('content',[]) if isinstance((m.get('message',{}) or {}).get('content'),list) else []:
                if c.get('type')=='tool_use': cmds.append(c['input'].get('command') or c['name'])
    return cmds
res=[]
for d in sorted(glob.glob(RUNS+'/*-*-*')):
    if not os.path.exists(d+'/time.json'): continue
    arm,task,rep=os.path.basename(d).split('-'); o=os.path.join(d,'out.mp4'); T=os.path.join(d,'_t'); os.makedirs(T,exist_ok=True)
    meta=json.load(open(d+'/out.json')) if os.path.getsize(d+'/out.json') else {}
    r=dict(arm=arm,task=task,rep=int(rep),cost=meta.get('total_cost_usd'),turns=meta.get('num_turns'),secs=json.load(open(d+'/time.json'))['secs'],
           sources_kept=all(sha(os.path.join(d,k))==v for k,v in SRC.items() if os.path.exists(os.path.join(d,k))))
    cmds=tools(meta.get('session_id',''),os.path.realpath(d)); r['bash']=len([c for c in cmds if isinstance(c,str) and ' ' in c])
    r['raw_ffmpeg']=sum(1 for c in cmds if isinstance(c,str) and re.search(r'(^|[;&|\s])ff(mpeg|probe)\s',c)); r['skill_scripts']=sum(1 for c in cmds if isinstance(c,str) and 'scripts/' in c and '.py' in c)
    ok=os.path.exists(o) and decodes(o); r['made']=ok; chk={}
    if ok:
        p=probe(o); r['probe']=p
        if task=='cut':
            chk['dur']=abs(p['dur']-5)<=0.1; chk['audio']=p['audio']
            chk['start_frame']=psnr(frame(o,0,T+'/o.png'),frame(MEDIA+'/src.mp4',3,T+'/s.png'))>=30
        if task=='vertical':
            chk['size']=(p['w'],p['h'])==(1080,1920); chk['dur']=abs(p['dur']-10)<=0.1; chk['audio']=p['audio']; b=bars(o); chk['no_bars']=b==('1080','1920')
        if task=='captions':
            chk['size']=(p['w'],p['h'])==(1920,1080); chk['dur']=abs(p['dur']-10)<=0.1
            fo,fs=frame(o,2,T+'/o.png'),frame(MEDIA+'/src.mp4',2,T+'/s.png')
            bot=psnr(fo,fs,'crop=iw:ih/3:0:ih*2/3'); top=psnr(fo,fs,'crop=iw:ih/2:0:0'); r['psnr_bot_top']=(bot,top)
            chk['text_at_2s']=bot<top-5
            g=psnr(frame(o,4.5,T+'/o2.png'),frame(MEDIA+'/src.mp4',4.5,T+'/s2.png'),'crop=iw:ih/3:0:ih*2/3'); chk['clear_at_4_5s']=g>=bot+5
        if task=='loudness':
            L=lufs(o); r['lufs']=L; chk['lufs']=L is not None and abs(L+14)<=1; chk['video']=p['w']==1920; chk['dur']=abs(p['dur']-10)<=0.1
        if task=='join':
            chk['dur']=abs(p['dur']-9.5)<=0.15; chk['audio']=p['audio'] and abs(p['adur']-9.5)<=0.2
            chk['starts_a']=psnr(frame(o,1,T+'/o1.png'),frame(MEDIA+'/a.mp4',1,T+'/a1.png'))>=30
            chk['ends_b']=psnr(frame(o,9,T+'/o2.png'),frame(MEDIA+'/b.mp4',3.5,T+'/b2.png'))>=30
            m=frame(o,5.75,T+'/om.png'); chk['blend']=psnr(m,frame(MEDIA+'/a.mp4',5.75,T+'/am.png'))<30 and psnr(m,frame(MEDIA+'/b.mp4',0.25,T+'/bm.png'))<30
        if task=='silence':
            chk['dur']=7.5<=p['dur']<=9.5; chk['no_pauses']=silences(o)==0; chk['av_match']=p['audio'] and abs(p['vdur']-p['adur'])<=0.2
    r['checks']=chk; r['pass']=ok and all(chk.values()) and r['sources_kept']
    res.append(r)
json.dump(res,open(os.path.join(os.path.dirname(RUNS.rstrip('/')),'results.json'),'w'),indent=1)
import collections
for arm in ['plain','skill']:
    rs=[x for x in res if x['arm']==arm]
    print(arm,'pass',sum(x['pass'] for x in rs),'/',len(rs),'cost',round(sum(x['cost'] or 0 for x in rs),3),'raw_ffmpeg runs',sum(1 for x in rs if x['raw_ffmpeg']))
    for t in ['cut','vertical','captions','loudness','join','silence']:
        q=[x for x in rs if x['task']==t]; print('  ',t,sum(x['pass'] for x in q),'/',len(q),[ {k:v for k,v in x['checks'].items() if not v} for x in q if not x['pass']])
