"""Authorized adaptive adoption; retains full component and shared weight draws."""
from pathlib import Path
import sys,json,inspect,textwrap
ROOT=Path(__file__).resolve().parents[2];A=Path(__file__).resolve().parent
REPAIR=ROOT/'audit/poll_panel_repair_2026-10-29';LIVE=A;PREV=ROOT/'audit/expert_alignment_adaptive_blend_2026-10-29'
sys.path[:0]=[str(ROOT/'repair_dependencies/stacking'),str(A),str(REPAIR),str(PREV),str(LIVE),str(ROOT/'audit/individual_adoption_2026-10-26/engine'),str(ROOT/'audit/individual_adoption_2026-10-26/combined')]
import numpy as np
import run_research as h
from research_model import ResearchModel
from joint_model import *
from polling_adapter import load_cycle
import importlib.util as _local_import
_poll_spec=_local_import.spec_from_file_location('oct30_runtime_poll_covariance',A/'polling_adapter.py')
_poll_module=_local_import.module_from_spec(_poll_spec);_poll_spec.loader.exec_module(_poll_module)
load_cycle=_poll_module.load_cycle
OLD=ROOT/'audit/individual_adoption_2026-10-26'
OUT=A/'combined'
source=textwrap.dedent(inspect.getsource(BaseModel.centers)) if 'BaseModel' in globals() else textwrap.dedent(inspect.getsource(h.joint.Model.centers))
source=source.replace('nodes,ghw=np.polynomial.hermite.hermgauss(24);','self.component_draws=np.zeros((n,len(rr),3));nodes,ghw=np.polynomial.hermite.hermgauss(24);')
a=';out[:,ix[j]]=wc[:,fi]*fundamental_draw+wc[:,ri]*Rdraw'
b=';self.component_draws[:,ix[j],0]=C[0] if d==3 else 0.;self.component_draws[:,ix[j],1]=fundamental_draw;self.component_draws[:,ix[j],2]=Rdraw;out[:,ix[j]]=wc[:,fi]*fundamental_draw+wc[:,ri]*Rdraw'
assert source.count(a)==1;source=source.replace(a,b);scope=dict(vars(h.joint));exec(source,scope);captured=scope['centers']
class Model(ResearchModel):
 mode='masked'
 def __init__(self,components=None):
  super().__init__(components if components is not None else read(REPAIR/'historical_components.csv'))
  self.adaptive=json.loads((A/'adaptive_posterior_2026.json').read_text());self.metadata={(r['chamber'],r['race']):r for r in read(A/'current_metadata.csv')}
 def features(self,rows):
  C=np.array([h.components(r)[0] for r in rows]);av=np.array([h.components(r)[1] for r in rows]);s=np.array([float(self.metadata[r['chamber'],r['race']]['verified_poll_strength']) for r in rows]);d=np.zeros_like(C)
  for i,r in enumerate(rows):d[i]=np.minimum(abs(C[i]-np.median(C[i,av[i]>0]))/10,3)
  for i,r in enumerate(rows):
   if r['chamber']=='Senate' and r['state']=='MT':s[i]=0.;d[i]=0.
  return C,av,s,d
 def point_weights(self,rows):
  C,av,s,d=self.features(rows);theta=np.array(self.adaptive['grid']);prob=np.array(self.adaptive['posterior']);out=[]
  for i,r in enumerate(rows):
   W,pg,cp=self.weight_posterior(2026,float(r['surveys'])>0);mass=pg@cp[r['group']];W=W if W.shape[1]==3 else np.column_stack([np.zeros(len(W)),W]);w=np.zeros(3)
   for p,t in zip(prob,theta):w+=p*(mass@h.tilt(W,np.repeat(s[i],len(W)),np.tile(d[i],(len(W),1)),t,np.tile(av[i],(len(W),1))))
   out.append(w if float(r['surveys'])>0 else w[1:])
  return out
 def centers(self,rows,cy,n=4096,seed=1,case='learned_mean_hier',current_fits=None):
  captured(self,rows,cy,n,seed,case,current_fits);D=self.component_draws.copy();C,av,s,d=self.features(rows);ids=[i for i,r in enumerate(rows) if r['chamber']=='House' and float(r['surveys'])>0]
  if ids:
   block=load_cycle(2026);idx={x:i for i,x in enumerate(block['races'])};ii=[idx[rows[i]['race']] for i in ids];factor=psd(block['covariance'][np.ix_(ii,ii)]);D[:,ids,0]-=np.random.default_rng(seed+7000000).normal(size=(n,len(ids)))@factor.T
  weights=np.stack([self.last_weight_draws[r['group']] if len(array(r['component_centers']))==3 else np.column_stack([np.zeros(n),self.last_weight_draws[r['group']]]) for r in rows],axis=1)
  theta=np.array(self.adaptive['grid'])[np.random.default_rng(seed+8100000).choice(len(self.adaptive['grid']),n,p=self.adaptive['posterior'])]
  weights=h.tilt(weights,s,d,theta,av);self.last_race_weights=weights
  return np.sum(weights*D,axis=2)

def prepare():
 rows=read(LIVE/'combined/current_components.csv');bias=json.loads((ROOT/'audit/adaptive_adoption_2026-10-29/combined/current_component_manifest.json').read_text())['new_senate_pooled_correction']
 for r in rows:
  if r['chamber']=='Senate' and float(r['surveys'])>0:
   c=array(r['component_centers']);c[0]=float(r['raw_poll'])+bias;r['component_centers']=json.dumps(c.tolist());r['poll_bias_adjustment']=bias
 m=Model()
 for r,w in zip(rows,m.point_weights(rows)):r['effective_mean_weights']=json.dumps(w.tolist());r['prediction']=float(w@array(r['component_centers']))
 OUT.mkdir(exist_ok=True);write(OUT/'current_components.csv',rows);save(OUT/'current_component_manifest.json',dict(as_of='2026-11-02',polling_as_of='2026-11-02',rows=470,method='Dynamic fundamentals and adaptive verified-strength learned blend',historical_repair=str(REPAIR),new_senate_pooled_correction=bias))
 print(json.dumps(dict(status='prepared',rows=len(rows),senate_bias=bias)),flush=True)
if __name__=='__main__':prepare()
