from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
import re,json

work=Path(__file__).parent
seed=(work/'app/supabase/migrations/20260821000000_baseline_v2.sql').read_text(encoding='utf-8')
points=[]
for load,reps,sd in re.findall(r"\('nuzzo-2024-general-inverse'::text, '1.0.0'::text, '([\d.]+)'::numeric\(8,4\), '([\d.]+)'::numeric\(10,4\), '([\d.]+)'::numeric\(10,4\)",seed):
    points.append((Decimal(load),Decimal(reps),Decimal(sd)))
assert len(points)==18
z=Decimal('1.2815515655446004')
def pct(reps,band):
    rows=[(load,mean+(z*sd if band=='high' else -z*sd if band=='low' else 0)) for load,mean,sd in points]
    lo=sorted((x for x in rows if x[1]<=reps),key=lambda x:(-x[1],x[0]))[0]
    hi=sorted((x for x in rows if x[1]>=reps),key=lambda x:(x[1],-x[0]))[0]
    result=lo[0] if lo[1]==hi[1] else lo[0]+(reps-lo[1])/(hi[1]-lo[1])*(hi[0]-lo[0])
    return result.quantize(Decimal('.000001'),rounding=ROUND_HALF_UP)
def estimate(load,reps,result,rpe):
    rir=Decimal(0) if result=='rep_failure' or rpe is None else 10-Decimal(rpe)
    effective=Decimal(reps)+rir
    supported=min(effective,Decimal(20))
    confidence='high' if reps==1 and rpe is not None and Decimal(rpe)>=10 else 'medium' if effective<=20 and (result=='rep_failure' or (rpe is not None and Decimal(rpe)>=6)) else 'low'
    raw=Decimal(load)*100/pct(supported,'center')
    return {'load':load,'reps':reps,'set_result':result,'rpe':rpe,'effective_reps':str(effective),'center_percent':str(pct(supported,'center')),'unrounded_e1rm':str(raw),'rounded_e1rm':str(raw.quantize(Decimal(1),rounding=ROUND_HALF_UP)),'confidence':confidence}
cases=[estimate('.10',12,'completed','7'),estimate('20',5,'rep_failure',None),estimate('.49',1,'completed','10'),estimate('999999.99',20,'rep_failure',None)]
votes=sorted(cases[:2],key=lambda x:Decimal(x['rounded_e1rm']))
weight=Decimal(0)
selected=None
for vote in votes:
    weight+=2
    if weight>=2:
        selected=vote['rounded_e1rm'];break
out={'method':'Independent Decimal arithmetic replay of interpolation/rounding and two equal-weight median. Fixture is the repository baseline curve data, not Production query and not PostgreSQL function execution. Current function inspected separately.','fixture':'supabase/migrations/20260821000000_baseline_v2.sql:31267-31292','app_commit':'0a6e4cdd6207423f27e4d5de5333a2d4e593488a','cases':cases,'two_vote_median_kg':selected,'small_positive_load_zero_threshold_kg_for_effective_reps_1_to_20':{'min':str(pct(Decimal(20),'center')/200),'max':str(pct(Decimal(1),'center')/200)},'unverified':'Live curve data, SQL execution, constraints, full worker and UI not exercised.'}
(work/'server-math-experiment.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(out,ensure_ascii=False,indent=2))
