from fractions import Fraction as F
import json
from pathlib import Path
p=Path(__file__).parent
d=json.loads((p/'ranking-sensitivity-fixtures.json').read_text())
checks=[]
for c in d['cases']:
    weights=[F(str(x)) for x in c['weights']]
    invalid=any(w<0 for w in weights) or sum(weights)<=0 or any(x is not None and not 0<=x<=100 for x in c['a']+c['b'])
    if 'expected_error' in c:
        assert invalid,c['id'];checks.append(c['id']);continue
    assert not invalid
    w=[x/sum(weights) for x in weights]
    def bounds(v):
        lower=sum((wi*F(str(x)) for wi,x in zip(w,v) if x is not None),F(0))
        missing=sum((wi for wi,x in zip(w,v) if x is None),F(0))
        return lower,lower+100*missing,missing
    a,au,am=bounds(c['a']);b,bu,bm=bounds(c['b']);e=c['expected']
    for key,actual in [('a_score',a),('b_score',b),('a_lower',a),('a_upper',au),('a_missing_weight_percent',100*am),('difference_a_minus_b',a-b)]:
        if key in e: assert actual==F(str(e[key])),(c['id'],key,str(actual))
    for key,actual in [('a_score_fraction',a),('b_score_fraction',b)]:
        if key in e:assert actual==F(e[key]),(c['id'],key)
    if 'a_exceeds_gate' in e: assert (100*am>d['default_max_missing_weight_percent'])==e['a_exceeds_gate']
    if e.get('ranking')=='unresolved':assert a<=b<=au and am>0
    if e.get('ranking')=='not-rated':assert 100*am>25
    checks.append(c['id'])
q=F(3,8)
w=[(1-q)*F(35,75),q,(1-q)*F(20,75),(1-q)*F(20,75)]
a=sum(x*y for x,y in zip(w,[82,75,80,85]));b=sum(x*y for x,y in zip(w,[77,90,70,70]))
assert a==b==F(1909,24)
checks.append('analytic-crossover-37.5-percent')
result={'evidence_type':'synthetic','method':'Independent Python fractions arithmetic','checks_passed':len(checks),'checks':checks,'network_requests':0,'provider_tests':0}
(p/'ranking-sensitivity-arithmetic-verification.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result))
