"""Actual foundation-model sklearn adapters; no pretrained dummy substitutes."""
from __future__ import annotations
import time
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from .core import note, gpu_peak, reset_gpu_peak


def prior(y,alpha=1.):
    y=np.asarray(y,int);return float((int(y.sum())+alpha)/(len(y)+2*alpha))

class Estimator:
    def __init__(self,name,device='cuda',seed=29,n_estimators=8,batch_size=256,model_path=None,checkpoint_version=None,**kw):
        self.name=name;self.device=device;self.seed=int(seed);self.n_estimators=int(n_estimators);self.batch_size=int(batch_size);self.model_path=model_path;self.checkpoint_version=checkpoint_version;self.kw=kw
    def fit(self,X,y):
        self.classes_=np.unique(y)
        if len(self.classes_)<2 or len(y)<2:
            self.model_=None;self.fallback_=prior(y);note('FALLBACK',model=self.name,rows=len(y),positives=int(np.sum(y)),prior=self.fallback_,reason='single_class_or_empty');return self
        self.fallback_=None
        if self.name in ('hgb_matched','hgb_full'):
            self.model_=HistGradientBoostingClassifier(max_iter=180,max_leaf_nodes=31,learning_rate=.055,l2_regularization=1.,random_state=self.seed,early_stopping=False)
        elif self.name in ('tabicl_frozen','tabicl_ordinary','tabicl_chronological'):
            try:from tabicl import TabICLClassifier
            except ImportError as e:raise RuntimeError('TabICL not installed. pip install tabicl. Install models on the V100 machine.') from e
            options=dict(n_estimators=self.n_estimators,batch_size=self.batch_size,random_state=self.seed,device=self.device,use_amp=self.device.startswith('cuda'),use_fa3=False)
            if self.model_path:options['model_path']=str(self.model_path)
            if self.checkpoint_version:options['checkpoint_version']=self.checkpoint_version
            self.model_=TabICLClassifier(**options)
        elif self.name=='tabpfn_35_frozen':
            try:from tabpfn import TabPFNClassifier
            except ImportError as e:raise RuntimeError('TabPFN not installed. Install package/weights in permitted research environment.') from e
            # The installed TabPFN version selects its own default checkpoint unless configured explicitly.
            # Never claim 3.5 unless version identity is established by runtime.
            opts=dict(device=self.device,n_estimators=self.n_estimators,random_state=self.seed)
            if self.model_path:opts['model_path']=str(self.model_path)
            self.model_=TabPFNClassifier(**opts)
        else:raise ValueError(self.name)
        note('MODEL',name=self.name,version=str(type(self.model_)),seed=self.seed,checkpoint=self.model_path or self.checkpoint_version or 'library_default_CHECK_VERSION',support_rows=len(y))
        self.model_.fit(np.asarray(X,np.float32),np.asarray(y,int));return self
    def predict(self,X):
        if self.fallback_ is not None:return np.full(len(X),self.fallback_,float)
        out=self.model_.predict_proba(np.asarray(X,np.float32));cl=np.asarray(self.model_.classes_)
        if 1 not in cl:raise AssertionError('Positive class mapping absent')
        p=np.asarray(out[:,int(np.flatnonzero(cl==1)[0])],float)
        if not np.isfinite(p).all():raise ValueError('Model produced NaN/Inf')
        return np.clip(p,0,1)
