"""Original exact one-dimensional Wasserstein CDF and quarter-mass flow oracle."""
from fractions import Fraction as F
from itertools import permutations
import json

def distribution(values,weights):
 if type(values) is not list or type(weights) is not list or not 1<=len(values)<=4 or len(values)!=len(weights) or any(type(x) not in [int,F] or abs(x)>10 for x in values) or any(type(x) not in [int,F] or not 0<=x<=10 for x in weights) or sum(weights)<=0:raise ValueError('1..4 bounded exact supports, nonnegative weights with positive total')
 total=F(sum(weights));out={}
 for x,v in zip(values,weights):out[F(x)]=out.get(F(x),F(0))+F(v)/total
 return out,total

def distance(xs,ws,ys,vs):
 p,pt=distribution(xs,ws);q,qt=distribution(ys,vs);cuts=sorted(set(p)|set(q));rows=[];total=F(0)
 for left,right in zip(cuts,cuts[1:]):
  cp=sum(v for x,v in p.items() if x<=left);cq=sum(v for x,v in q.items() if x<=left);area=abs(cp-cq)*(right-left);total+=area;rows.append({'left':str(left),'right':str(right),'CDF_P':str(cp),'CDF_Q':str(cq),'absolute_gap':str(abs(cp-cq)),'area':str(area)})
 return total,rows,{'input_P_weight_total':str(pt),'input_Q_weight_total':str(qt),'positive_totals_normalized':True}

def demo():
 xs=[0,2];ws=[F(1,2)]*2;ys=[1,3];vs=[F(3,4),F(1,4)];d,rows,normal=distance(xs,ws,ys,vs);assert d==1 and [r['area'] for r in rows]==['1/2','1/4','1/4']
 flows=[]
 for a in range(5):
  for b in range(5):
   for c in range(5):
    for e in range(5):
     if a+b==2 and c+e==2 and a+c==3 and b+e==1:
      mass=[[a,b],[c,e]];cost=sum(F(mass[i][j],4)*abs(xs[i]-ys[j]) for i in range(2) for j in range(2));flows.append({'quarter_unit_flow_matrix':mass,'cost':str(cost)})
 assert len(flows)==2 and sorted(F(r['cost']) for r in flows)==[1,F(3,2)] and min(F(r['cost']) for r in flows)==d
 invariants=[]
 for shift,scale in [(0,1),(3,1),(0,2),(-2,F(1,2))]:
  actual,_,_=distance([scale*x+shift for x in xs],ws,[scale*y+shift for y in ys],vs);assert actual==scale*d;invariants.append({'shift':str(shift),'positive_scale':str(scale),'distance':str(actual)})
 permchecks=0
 for xp,yp in [(list(reversed(xs)),list(reversed(ys))), (xs,list(reversed(ys))),(list(reversed(xs)),ys)]:
  ww=list(reversed(ws)) if xp!=xs else ws;vv=list(reversed(vs)) if yp!=ys else vs;assert distance(xp,ww,yp,vv)[0]==d;permchecks+=1
 equal,_,_=distance(xs,ws,xs,ws);assert equal==0
 duplicated,_,_=distance([0,0,2],[1,1,2],ys,[3,1]);assert duplicated==d
 rejected=[]
 for label,a,b,c,e in [('negative_weight',xs,[-1,2],ys,vs),('zero_total',xs,[0,0],ys,vs),('mismatch',xs,[1],ys,vs),('nonfinite_support',[0,float('inf')],ws,ys,vs),('nonfinite_weight',xs,[1,float('nan')],ys,vs),('over_budget',list(range(5)),[1]*5,ys,vs)]:
  try:distance(a,b,c,e)
  except ValueError:rejected.append(label)
  else:raise AssertionError('expected rejection')
 return {'P_support':xs,'P_weights':[str(x) for x in ws],'Q_support':ys,'Q_weights':[str(x) for x in vs],'CDF_interval_areas':rows,'W1':str(d),'normalization':normal,'independent_all_feasible_quarter_mass_flows':flows,'translation_positive_scale_checks':invariants,'support_permutations_checked':permchecks,'identical_distribution_distance':str(equal),'duplicate_locations_aggregated_normalized':str(duplicated),'invalid_cases_rejected':rejected,'scope':'own exact 1D discrete law, mass splitting allowed, distance in support-axis units; no multivariate optimization/SciPy run/population test/drift threshold/auto-retrain or one-to-one assignment'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
