"""Authored retrieval arithmetic. No model, embedding, index or database execution."""
import json,hashlib,sys
from pathlib import Path
from fractions import Fraction
from datetime import datetime,timezone
ROOT=Path(__file__).resolve().parent
def ids(value):
    if not isinstance(value,list) or any(not isinstance(x,str) or not x for x in value) or len(set(value))!=len(value):raise ValueError('invalid_identifiers')
    return value
def evaluate(rows,k):
    if type(k) is not int or k<=0:raise ValueError('invalid_cutoff')
    ids([r['id'] for r in rows]);out=[];totals={p:[] for p in ['baseline','candidate']}
    for row in rows:
        raw=row.get('relevant');relevant=set(ids([] if raw is None else raw));hits={};paths={}
        for p in totals:
            rank=ids(row[p]);hits[p]=relevant.intersection(rank[:k])
            score=Fraction(len(hits[p]),len(relevant)) if relevant else None
            if score is not None:totals[p].append(score)
            paths[p]=dict(recall=str(score) if score is not None else None,retrieved_relevant=sorted(hits[p]),missing_relevant=sorted(relevant-hits[p]))
        out.append(dict(id=row['id'],status='judged' if relevant else 'unjudged',**paths,lost=sorted(hits['baseline']-hits['candidate']),shared_missed=sorted(relevant-hits['baseline']-hits['candidate'])))
    return dict(cutoff=k,judged=len(totals['baseline']),unjudged=len(rows)-len(totals['baseline']),macro={p:str(sum(v,Fraction())/len(v)) if v else None for p,v in totals.items()},queries=out)
def vector_bytes(n,d):
    if type(n) is not int or n<0 or type(d) is not int or d<=0:raise ValueError('invalid_storage_assumptions')
    return n*(4*d+8)
def boundaries():
    count=0
    def check(test):
        nonlocal count
        assert test;count+=1
    def rejected(fn):
        nonlocal count
        try:fn()
        except ValueError:count+=1
        else:raise AssertionError('invalid input accepted')
    r=dict(id='q',relevant=['a'],baseline=[],candidate=['x'])
    check(evaluate([r],3)['macro']==dict(baseline='0',candidate='0'))
    u=dict(r,relevant=None)
    check(evaluate([u],3)['macro']==dict(baseline=None,candidate=None))
    check(evaluate([dict(r,baseline=['x','a'])],1)['macro']['baseline']=='0')
    rejected(lambda:evaluate([r,r],3))
    rejected(lambda:evaluate([dict(r,relevant=['a','a'])],3))
    rejected(lambda:evaluate([dict(r,baseline=['a','a'])],3))
    rejected(lambda:evaluate([r],0))
    rejected(lambda:vector_bytes(1,0))
    check(vector_bytes(0,256)==0)
    return count
if __name__=='__main__':
    f=json.loads((ROOT/'fixture.json').read_text());result=evaluate(f['queries'],f['cutoff'])
    assert result['macro']==f['expected_macro'] and result['judged']==3 and result['unjudged']==1
    assert result['queries'][0]['lost']==['b'] and result['queries'][2]['shared_missed']==['e']
    assert evaluate(list(reversed(f['queries'])),f['cutoff'])['macro']==result['macro']
    tests=boundaries()+1
    s=f['storage'];storage={str(d):vector_bytes(s['count'],d) for d in s['dimensions']};assert storage==f['expected_storage_bytes']
    record=dict(author='Anant Mishra',status='executed_synthetic_retrieval_arithmetic',executed_at_utc=datetime.now(timezone.utc).isoformat(),python_version=sys.version,command='python3 reproduce.py',hashes={n:hashlib.sha256((ROOT/n).read_bytes()).hexdigest() for n in ['fixture.json','reproduce.py']},boundary_checks=tests,retrieval=result,vector_value_bytes=storage,limitations='Hand-written rankings independent of hypothetical dimensions. No model, encoder, index, database size, timing, answer quality or operational cost measured.')
    print(json.dumps(record,indent=2))
