"""Frozen-prediction scorer; never fits models or certifies registration.
Original code: Christopher Hill / NetPhysics, AI-assisted. MIT.
python evaluate.py predictions.csv analysis-plan.json results.json
"""
from pathlib import Path
import csv,json,math,hashlib,argparse
import numpy as np

def evaluate(rows,plan):
    models=[plan['candidate']]+plan['rivals'];marg=float(plan['minimum_relative_rmse_improvement']);cap=float(plan['maximum_normalized_rmse']);alpha=float(plan['family_alpha'])
    if len(set(models))!=len(models) or len(models)<2:raise ValueError('Distinct candidate and rival names required')
    if not 0<marg<1 or not math.isfinite(cap) or not 0<cap or not 0<alpha<1:raise ValueError('Invalid decision margins')
    minimum_units=int(plan['minimum_independent_units'])
    if minimum_units<2:raise ValueError('At least two independent units must be required')
    if not rows:raise ValueError('No prediction rows')
    kinds={r['data_kind'] for r in rows}
    if len(kinds)!=1 or not kinds<={'synthetic','measured'}:raise ValueError('Declare one data kind')
    if any(r['split']!='test' for r in rows):raise ValueError('Only frozen test predictions may be scored')
    specimens=sorted({r['specimen_id'] for r in rows});clusters=sorted({r['cluster_id'] for r in rows});draws=sorted({r['draw_id'] for r in rows})
    if any(not r[k].strip() for r in rows for k in ['specimen_id','cluster_id','point_id','draw_id']):raise ValueError('Missing identifiers')
    if len(clusters)<2:raise ValueError('At least two independent sampling units needed for an interval')
    if set(specimens)&set(plan['calibration_specimen_ids']):raise ValueError('Calibration/test specimen leakage')
    if set(clusters)&set(plan['calibration_cluster_ids']):raise ValueError('Calibration/test cluster leakage')
    cells={};speccluster={}
    for r in rows:
        key=(r['draw_id'],r['specimen_id'],r['point_id'])
        if key in cells:raise ValueError('Duplicate prediction key')
        if r['specimen_id'] in speccluster and speccluster[r['specimen_id']]!=r['cluster_id']:raise ValueError('Specimen assigned to different sampling units')
        speccluster[r['specimen_id']]=r['cluster_id']
        rr={k:float(r[k]) for k in ['force_N','reference_force_N','sigma_N','weight']+models}
        if not all(math.isfinite(x) for x in rr.values()):raise ValueError('Nonfinite observation or prediction')
        if any(rr[k]<=0 for k in ['reference_force_N','sigma_N','weight']):raise ValueError('Positive reference, uncertainty and integration weight required')
        cells[key]=rr
    expected={(s,p) for d,s,p in cells if d==draws[0]}
    for d in draws:
        if {(s,p) for dd,s,p in cells if dd==d}!=expected:raise ValueError('Every calibration draw must contain every test point')
        for s in specimens:
            if len({v['reference_force_N'] for (dd,ss,p),v in cells.items() if dd==d and ss==s})!=1:raise ValueError('Reference force must be constant within a specimen and calibration draw')
    # Keep the same sampling design across joint calibration draws.
    for s,p in expected:
        if len({cells[(d,s,p)]['weight'] for d in draws})!=1:raise ValueError('Integration weights changed across draws')
    loss=np.empty((len(draws),len(clusters),len(models)));zloss=np.empty_like(loss)
    counts={c:sum(speccluster[s]==c for s in specimens) for c in clusters}
    for di,d in enumerate(draws):
        per_spec={};per_z={}
        for s in specimens:
            rr=[v for (dd,ss,p),v in cells.items() if dd==d and ss==s]
            w=np.array([r['weight'] for r in rr]);w=w/w.sum()
            per_spec[s]=[float(w@np.array([((r['force_N']-r[k])/r['reference_force_N'])**2 for r in rr])) for k in models]
            per_z[s]=[float(w@np.array([((r['force_N']-r[k])/r['sigma_N'])**2 for r in rr])) for k in models]
        for ci,c in enumerate(clusters):
            ss=[s for s in specimens if speccluster[s]==c]
            loss[di,ci]=np.mean([per_spec[s] for s in ss],axis=0);zloss[di,ci]=np.mean([per_z[s] for s in ss],axis=0)
    # Equal weight for independent sampling units; each draw is joint across all units.
    mean=loss.mean(axis=(0,1));rmse=np.sqrt(mean)
    if np.any(mean[1:]<=0):raise ValueError('Relative improvement is undefined for a zero-loss rival')
    gain=1-rmse[0]/rmse[1:]
    reps=int(plan['bootstrap_replicates']);seed=int(plan['seed'])
    if reps<1000:raise ValueError('Use at least 1000 replicates; inspect Monte Carlo stability before confirmation')
    rng=np.random.default_rng(seed);boot=np.empty((reps,len(models)))
    for b in range(reps):
        di=rng.integers(len(draws));ix=rng.integers(len(clusters),size=len(clusters));q=loss[di,ix].mean(axis=0)
        if np.any(q[1:]<=0):raise ValueError('Zero rival bootstrap loss prevents a ratio interval')
        boot[b,0]=math.sqrt(q[0]);boot[b,1:]=1-math.sqrt(q[0])/np.sqrt(q[1:])
    # One interval per rival plus one absolute-accuracy criterion.
    tail=alpha/(2*len(models));lo,hi=np.quantile(boot,[tail,1-tail],axis=0)
    enough=len(clusters)>=minimum_units
    numerical_screen=bool(enough and hi[0]<cap and np.all(lo[1:]>marg))
    caveats=['Percentile intervals are approximate, not an exact finite-sample coverage guarantee.','Equal independent-unit weighting is the estimand; repeated points do not increase N.','A good relative score can coexist with inadequate absolute accuracy.','Standardized residual RMS is diagnostic only; it is not chi-square or a covariance-aware likelihood.','No claim that a submission, registration or external review exists is inferred from a configuration file.']
    if len(draws)==1:caveats.append('One calibration draw: intervals are conditional on fixed calibration and prediction parameters; common calibration uncertainty is not propagated.')
    else:caveats.append('Joint calibration draws must come only from independent calibration/pilot data and carry shared dependencies; their validity is supplied, not verified by this scorer.')
    if len(clusters)<20:caveats.append('Fewer than 20 independent units: interval reliability needs particular scrutiny.')
    status='Synthetic software fixture only' if kinds=={'synthetic'} else 'Measured conditional comparison; design and calibration audit required'
    return {'status':status,'data_kind':next(iter(kinds)),'specimens':len(specimens),'independent_sampling_units':len(clusters),'calibration_draws':len(draws),'point_rows_per_draw':len(expected),'unit_specimen_counts':counts,'normalized_rmse':dict(zip(models,map(float,rmse))),'standardized_residual_rms':dict(zip(models,map(float,np.sqrt(zloss.mean(axis=(0,1)))))),'candidate_absolute_rmse_interval':[float(lo[0]),float(hi[0])],'comparisons':{k:{'relative_rmse_improvement':float(gain[i]),'simultaneous_interval':[float(lo[i+1]),float(hi[i+1])]} for i,k in enumerate(models[1:])},'minimum_relative_improvement':marg,'maximum_normalized_rmse':cap,'interval_family_size':len(models),'family_alpha':alpha,'per_interval_coverage_nominal':1-alpha/len(models),'bootstrap_replicates':reps,'seed':seed,'proposed_numerical_screen_passed':numerical_screen,'confirmatory_evidence_claimed':False,'caveats':caveats}

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('predictions',type=Path);p.add_argument('plan',type=Path);p.add_argument('output',type=Path);a=p.parse_args()
    with a.predictions.open(newline='') as f:rows=list(csv.DictReader(f))
    result=evaluate(rows,json.loads(a.plan.read_text()));result['input_sha256']={x.name:hashlib.sha256(x.read_bytes()).hexdigest() for x in [a.predictions,a.plan]}
    a.output.write_text(json.dumps(result,indent=2,allow_nan=False)+'\n');print(result['status'])
