#!/usr/bin/env python3
"""Save real hybrid/vector searches and required creature ranking assertions."""
import json, sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'lib'))
from search import Search
import embeddings as e

def main():
    out=ROOT/'W-LIBCARDS-evidence';s=Search(ROOT);calls={'joint':0,'description':0}
    mm,tx=e.multimodal,e.text_vector
    def counted_mm(*args,**kw):calls['joint']+=1;return mm(*args,**kw)
    def counted_tx(*args,**kw):calls['description']+=1;return tx(*args,**kw)
    e.multimodal=counted_mm;e.text_vector=counted_tx
    proof={}
    for query in ('realistic grey wolf','deer','orc','a horned bull','elephant'):
        proof[query]=s.search(query,limit=5)
    fox='animal.canine.fox/omg-fox-realistic'
    proof['like realistic fox']=s.search(like=fox,limit=5)
    proof['image realistic fox']=s.search(image=ROOT/s.byid[fox]['thumbnail'],limit=5)
    checks={
        'realistic_wolf_first':proof['realistic grey wolf']['results'][0]['id']=='animal.canine.wolf/omg-wolf-realistic',
        'deer_and_stag': {'animal.deer.deer','animal.deer.stag'} <= {a['class'] for a in proof['deer']['results']},
        'orc':proof['orc']['results'][0]['class']=='monster.humanoid.orc',
        'horned_bull':proof['a horned bull']['results'][0]['class']=='animal.livestock.bull',
        'fox_like_animals':all(a['class'].startswith('animal.') for a in proof['like realistic fox']['results']),
        'fox_like_canines':any(a['class'].startswith('animal.canine.') for a in proof['like realistic fox']['results']),
        'fox_image_first':proof['image realistic fox']['results'][0]['id']==fox,
        'elephant_gap':not proof['elephant']['results'] and proof['elephant']['gaps']==['animal.wildlife.elephant'],
    }
    (out/'search-proof.json').write_text(json.dumps({'queries':proof,'checks':checks,'query_model_calls':calls},indent=1))
    for query,r in proof.items():
        print(query + (' GAP '+','.join(r['gaps']) if r['gaps'] else '\n  '+'\n  '.join(f"{a['score']:.5f} {a['id']}" for a in r['results'])))
    print('CHECKS',json.dumps(checks));print('Query model calls',calls)
    if not all(checks.values()):raise SystemExit('Search proof failed; see search-proof.json')
if __name__=='__main__':main()
