"""Simple protocol-strength model: F_p = R^k / (R^k + R50_p^k).

One shared capability-ratio slope, one intercept per protocol. Defender scores
are complemented onto a reported-failure proxy; original event labels remain.
No time, study, model-specific, metric or context effects. Time is inspected
by plotting protocol strengths at their publication dates, not fitted as a term.
Run: OPENBLAS_NUM_THREADS=1 python simple_control.py
"""
from __future__ import annotations
import json
import math
import numpy as np
from scipy.special import log_ndtr
import ai_control as archive


def arrays(rows, protocols):
    index={p:i for i,p in enumerate(protocols)}
    group=np.array([index[o['protocol']] for o in rows])
    x=-np.array([o['ln_attacker']-o['ln_monitor'] for o in rows])
    sd=np.array([o['logit_sd'] for o in rows])
    exact=np.array(['value' in o for o in rows])
    y=np.array([archive.logit(o.get('value',o.get('upper',o.get('lower',.5)))) for o in rows])
    lower=np.array([archive.logit(o['lower']) if 'lower' in o else -np.inf for o in rows])
    upper=np.array([archive.logit(o['upper']) if 'upper' in o else np.inf for o in rows])
    return group,x,sd,exact,y,lower,upper


def posterior(rows, protocols, draws=5000, burn=2500, chains=4):
    group,x,sd,exact,y0,lower,upper=arrays(rows,protocols)
    weights=1/sd**2
    denominator=1/16+np.bincount(group,weights=weights,minlength=len(protocols))
    precision=np.diag(weights)
    for g in range(len(protocols)):
        ids=np.flatnonzero(group==g)
        precision[np.ix_(ids,ids)]-=np.outer(weights[ids],weights[ids])/denominator[g]
    loading=x@precision
    slope_sd=1/math.sqrt(loading@x+1/.64)
    latent_sd=1/np.sqrt(precision.diagonal())
    censored=np.flatnonzero(~exact)
    output=[]
    for chain in range(chains):
        rng=np.random.default_rng(20261106+191*chain)
        slope=.6;y=y0.copy();kept=[]
        for step in range(draws+burn):
            if len(censored):
                residual=precision@(y-slope*x)
                for j in censored:
                    mean=y[j]-residual[j]*latent_sd[j]**2
                    new=archive.truncated_scalar(rng,mean,latent_sd[j],lower[j],upper[j])
                    residual+=precision[:,j]*(new-y[j]);y[j]=new
            slope_mean=(loading@y+.6/.64)*slope_sd**2
            slope=archive.truncated_scalar(rng,slope_mean,slope_sd,0,np.inf)
            if step>=burn:
                means=np.bincount(group,weights=weights*(y-slope*x),minlength=len(protocols))/denominator
                intercepts=rng.normal(means,1/np.sqrt(denominator))
                kept.append(np.r_[slope,intercepts])
        output.append(kept)
    return np.array(output)


def write_result(data,result):
    archive.save_section('simple_model',result)
    payload={**result,'observations':archive.model_observations(data),'sources':data['sources'],'variants':data['variants'],
             'capabilities':data['models'],'tested_pairs':data['tested_pairs'], 'frontier':data['frontier_plot']}
    (archive.ROOT.parents[1]/'ai_control_simple_data.js').write_text('// Generated by analysis/ai_control_growth/simple_control.py\nwindow.AI_CONTROL_SIMPLE = '+json.dumps(payload,separators=(',',':'))+';\n')


def main():
    data=archive.load_section('evidence');all_rows=archive.model_observations(data)
    eligible=[o for o in all_rows if o['attacker'] in data['models'] and o['monitor'] in data['models']
              and not o.get('extra_attack') and o.get('candidate_eligible',True)]
    models={};labels={v['id']:v['label'] for v in data['variants']}
    for metric in ['unified']:
        rows=eligible
        protocols=sorted({o['protocol'] for o in rows})
        samples=posterior(rows,protocols)
        rhat=archive.split_rhat(samples);effective=archive.ess(samples)
        flat=samples.reshape(-1,samples.shape[-1])
        chosen=np.random.default_rng(20261106).choice(len(flat),2000,replace=False)
        models[metric]={'slope':float(np.median(flat[:,0])),'slope_draws':np.round(flat[chosen,0],7).tolist(),
            'protocols':[{'id':p,'label':labels.get(p,p),'date':min(o['date'] for o in rows if o['protocol']==p),
                          'study':next(o['study'] for o in rows if o['protocol']==p),
                          'alpha':float(np.median(flat[:,j+1])), 'alpha_draws':np.round(flat[chosen,j+1],7).tolist(),
                          'observation_ids':[o['id'] for o in rows if o['protocol']==p],
                          'ratio_count':len({round(o['ln_attacker']-o['ln_monitor'],6) for o in rows if o['protocol']==p})}
                         for j,p in enumerate(protocols)],
            'observation_ids':[o['id'] for o in rows], 'study_count':len({o['study'] for o in rows}),
            'point_count':sum('value' in o for o in rows),'bound_count':sum('value' not in o for o in rows),
            'max_rhat':float(rhat.max()),'min_ess':float(effective.min())}
        print(metric,len(rows),'rows;',len(protocols),'protocols; slope',round(models[metric]['slope'],3),
              'max Rhat',round(rhat.max(),3),'min ESS',round(effective.min()),flush=True)
        if rhat.max()>=1.05 or effective.min()<=400:raise RuntimeError('Convergence checks failed')
    result={'formula':'F_p = R^k / (R^k + R50_p^k); R = A/M; F_p = 1 - S_p; R50_p = exp(alpha_p/k).',
            'method':'One shared nonnegative ratio slope and one intercept per protocol, fitting a common reported-failure proxy. No study, time, metric or context effects.',
            'outcome_unification':'The plotted outcome is 1 minus the reported defender score: unsafe outcome, missed attack, or episode not prevented. Pooling assumes these proxies share a capability-ratio response, conditional on protocol strength. Their original event definitions remain visible; a missed attack is not automatically successful harmful action. This is not a calibrated unified deployment-risk probability.',
            'uncertainty':'90% pointwise Bayesian credible intervals from four chains; observation rows are conditionally independent under the working likelihood. Repeated or correlated evidence can make these intervals optimistic.',
            'selection':'Fit observations with placed attacker and monitor capability estimates, excluding human attacks and baselines without trusted review. Other evidence stays in the inventory.',
            'evidenceDigest':archive.evidence_digest(data),'models':models}
    write_result(data,result)

if __name__=='__main__':main()
