#!/usr/bin/env python3
"""Known-sigma Gaussian log-regression checks; independent synthetic rows only."""
import csv,json,math,random,statistics
from pathlib import Path
import analysis as core

def losses(rows,coef,broken):
    return [(math.log(y)-sum(a*b for a,b in zip(coef,core.features(x,broken))))**2 for x,y,s in rows]

def information(rows,coef,broken):
    k=len(coef);n=len(rows)
    nll=0.5*sum(math.log(2*math.pi*s*s)+e/(s*s) for e,(_,_,s) in zip(losses(rows,coef,broken),rows))
    return 2*nll+2*k+2*k*(k+1)/(n-k-1)

def compare(train,test):
    a=core.fit(train,False);b=core.fit(train,True)
    la=losses(test,a,False);lb=losses(test,b,True);diff=[x-y for x,y in zip(la,lb)]
    rng=random.Random(81421)
    boot=sorted(statistics.mean(rng.choices(diff,k=len(diff))) for _ in range(5000))
    aa=information(train,a,False);ab=information(train,b,True)
    wb=1/(1+math.exp(max(-700,min(700,-0.5*(aa-ab)))))
    return dict(held_out_mse_difference_single_minus_hinge=statistics.mean(diff),
        conditional_paired_bootstrap_95_interval=[boot[124],boot[4874]],
        training_aicc_single=aa,training_aicc_hinge=ab,training_aicc_hinge_weight=wb)

def cv(rows):
    # Development folds only; existing fixed holdout is not used to tune models.
    output=[]
    for seed in range(20):
        idx=list(range(len(rows)));random.Random(9100+seed).shuffle(idx);diff=[]
        for k in range(5):
            held=set(idx[k::5]);tr=[r for j,r in enumerate(rows) if j not in held];te=[r for j,r in enumerate(rows) if j in held]
            a=core.fit(tr,False);b=core.fit(tr,True)
            diff.extend(x-y for x,y in zip(losses(te,a,False),losses(te,b,True)))
        output.append(statistics.mean(diff))
    return dict(repeats=20,folds=5,mean_mse_difference=statistics.mean(output),range_across_splits=[min(output),max(output)],
        warning='Repeated folds share data. The range is sensitivity to the split, not a confidence interval or 100 independent tests.')

def synthetic(seed,broken):
    rng=random.Random(seed);tr=[];te=[]
    for i in range(37):
        lx=5*i/36;ly=math.log(1.7)+0.6*lx+(0.55*max(0,lx-math.log(20)) if broken else 0)+rng.gauss(0,0.04)
        (te if i%4==2 else tr).append((math.exp(lx),math.exp(ly),0.04))
    return tr,te

def main():
    with (Path(__file__).parent/'synthetic-demo.csv').open() as f: raw=list(csv.DictReader(f))
    tr=[tuple(float(r[k]) for k in ['x_ratio','y_ratio','sigma_log_y']) for r in raw if r['split']=='train']
    te=[tuple(float(r[k]) for k in ['x_ratio','y_ratio','sigma_log_y']) for r in raw if r['split']=='test']
    ntr,nte=synthetic(70123,False)
    wins=0
    for seed in range(200):
        a,b=synthetic(80000+seed,False)
        wins+=core.mse(b,core.fit(a,True),True)<core.mse(b,core.fit(a,False),False)
    assert 0<wins<200
    return dict(status='Synthetic pipeline robustness, not a cross-system empirical test',positive_break_case=compare(tr,te),
        development_cross_validation=cv(tr),single_power_law_null=compare(ntr,nte),
        null_simulations=dict(count=200,hinge_lower_holdout_mse_count=wins,
        interpretation='No threshold applied. A more flexible model sometimes wins under the null; one lower error is not discovery.'),
        assumptions='Known independent Gaussian noise in log(y), equivalent to multiplicative lognormal error; x treated as exact. AICc is a small-sample penalized-likelihood diagnostic, not a held-out score. Conditional bootstrap fixes the trained models and assumes independent test rows; no device-level CI is claimed.',
        limitations='No measured residual distribution has been tested. Grouped systems, correlated errors and unknown noise require a different protocol; a histogram-tail power-law method is not this regression method.')

if __name__=='__main__':print(json.dumps(main(),indent=2,allow_nan=False))
