import hashlib
import itertools
import json
from inputs import OUT
from seed_follow import SeedFollow

contract=json.loads((OUT/'execution_contract.json').read_text());clips=contract['development']
assert not set(clips)&set(contract['holdout'])
data={};sources={};canon={}
for clip in clips:
    p=OUT/'work'/clip/'features.jsonl';raw=p.read_bytes();sources[clip]=hashlib.sha256(raw).hexdigest()
    rows=[json.loads(s) for s in raw.splitlines()]
    for i,r in enumerate(rows):
        if r['displayed']:canon[r['dedupe_key']]=min(canon.get(r['dedupe_key'],(clip,i)),(clip,i))
    data[clip]=rows
trials=[]
for speed,near,approach,count in itertools.product((.3,.5,.7),(.08,.14,.20),(.1,.3),(2,3)):
    cfg=dict(family='seed_follow',speed_min=speed,near_max=near,approach_speed_min=approach,extension_speed_min=0.,
        cosine_min=.45,foot_vertical_max=.4,min_samples=count,window=1.,seed_seconds=.6)
    result=dict(index=len(trials),config=cfg,primary_negative=0,other_negative=0,positive=0,positive_inputs=0,by_clip={})
    for clip,rows in data.items():
        engine=SeedFollow(cfg);ph=nh=pn=nn=0
        for i,r in enumerate(rows):
            v=engine.step(r)
            if not r['displayed'] or canon[r['dedupe_key']]!=(clip,i):continue
            if r['reference']=='positive_reference':pn+=1;ph+=v['hit']
            elif r['reference']=='negative_reference':nn+=1;nh+=v['hit']
        result['positive']+=ph;result['positive_inputs']+=int(ph>0)
        result['primary_negative' if clip.startswith(('02_','03_','14_')) else 'other_negative']+=nh
        result['by_clip'][clip]=dict(positive_hits=ph,positive_N=pn,negative_hits=nh,negative_N=nn)
    trials.append(result)
trials.sort(key=lambda v:(v['primary_negative'],v['other_negative'],-v['positive_inputs'],-v['positive']))
report=dict(status='DEVELOPMENT_COMPARISON_NOT_ACCEPTANCE',trials_data=trials,trials=len(trials),
    source_hashes=sources,holdout_opened=False,initial_search_sha256=hashlib.sha256((OUT/'reports/search.json').read_bytes()).hexdigest())
(OUT/'reports/search_seed_follow.json').write_text(json.dumps(report,indent=2))
print(json.dumps([{k:v[k] for k in ('index','config','primary_negative','other_negative','positive','positive_inputs')} for v in trials]),flush=True)
