# -*- coding: utf-8 -*-
from __future__ import annotations

from dataclasses import dataclass
import math
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import average_precision_score

from suite26_data import TreeArrays


def _positive_probability(model,X):
    p=np.asarray(model.predict_proba(X),float); c=np.asarray(model.classes_)
    hit=np.where(c==1)[0]
    if len(hit)!=1: raise RuntimeError('Positive class 1 missing from tree encoder')
    return np.clip(p[:,int(hit[0])],1e-6,1-1e-6).astype(np.float32)


def _node_depths(tree):
    left=tree.children_left; right=tree.children_right; depth=np.zeros(tree.node_count,np.int16); stack=[0]
    while stack:
        n=stack.pop(); l=int(left[n]); r=int(right[n])
        if l>=0: depth[l]=depth[n]+1; stack.append(l)
        if r>=0: depth[r]=depth[n]+1; stack.append(r)
    return depth


@dataclass
class TreeEncoderMetadata:
    leaf_stats:np.ndarray       # [vocab,4], id0 padding
    feature_importance:np.ndarray
    n_trees:int
    vocab_size:int
    tree_leaf_counts:np.ndarray


class TreeNativeEncoder:
    """Single strong ExtraTrees current-state learner plus compact leaf vocabulary.

    This is deliberately *not* the three-model Committee. The same forest supplies
    both an ordinary current-state risk score and the discrete tree partitions used
    by Suite26's neural memory interaction model.
    """
    def __init__(self,seed=42,n_estimators=96,max_leaf_nodes=1024,min_samples_leaf=4,max_features=.70,n_jobs=-1):
        self.seed=int(seed); self.model=ExtraTreesClassifier(
            n_estimators=int(n_estimators),min_samples_leaf=int(min_samples_leaf),max_features=float(max_features),
            max_leaf_nodes=int(max_leaf_nodes) if max_leaf_nodes else None,class_weight='balanced_subsample',
            bootstrap=True,oob_score=True,n_jobs=int(n_jobs),random_state=int(seed))
        self.maps=[]; self.meta=None; self.training_oob_score_=None; self.oob_ap_=None

    def fit(self,X,y):
        X=np.nan_to_num(np.asarray(X,np.float32),nan=0.,posinf=0.,neginf=0.); y=np.asarray(y,int)
        if np.unique(y).size<2: raise ValueError('TreeNativeEncoder requires both classes')
        self.model.fit(X,y); maps=[]; stats=[[0.,0.]]; counts=[]; gid=1
        oob=np.asarray(self.model.oob_decision_function_,float)
        if oob.ndim==2 and oob.shape[1]>=2:
            self.training_oob_score_=np.clip(oob[:,1],1e-6,1-1e-6).astype(np.float32)
            good=np.isfinite(self.training_oob_score_)
            if good.any() and np.unique(y[good]).size>1:self.oob_ap_=float(average_precision_score(y[good],self.training_oob_score_[good]))
        for est in self.model.estimators_:
            tr=est.tree_; leaves=np.where(tr.children_left<0)[0]; counts.append(len(leaves)); mp=np.zeros(tr.node_count,np.int32); depths=_node_depths(tr); md=max(int(depths.max()),1)
            for node in leaves:
                mp[int(node)]=gid
                sup=float(tr.n_node_samples[int(node)])
                # Do not inject in-sample leaf target rates into the downstream network.
                # Supervision enters through the learned leaf embedding and an OOB tree score.
                stats.append([math.log1p(sup),float(depths[int(node)])/md])
                gid+=1
            maps.append(mp)
        self.maps=maps
        self.meta=TreeEncoderMetadata(np.asarray(stats,np.float32),np.asarray(self.model.feature_importances_,np.float32),len(self.model.estimators_),gid,np.asarray(counts,np.int32))
        return self

    def transform(self,X,chunk_size=50000,progress=False,label='tree-transform'):
        if self.meta is None: raise RuntimeError('fit first')
        X=np.nan_to_num(np.asarray(X,np.float32),nan=0.,posinf=0.,neginf=0.); N=len(X); T=self.meta.n_trees
        leaves=np.empty((N,T),np.int32); score=np.empty(N,np.float32)
        for st in range(0,N,int(chunk_size)):
            en=min(N,st+int(chunk_size)); xx=X[st:en]
            raw=self.model.apply(xx)
            for t,mp in enumerate(self.maps):
                leaves[st:en,t]=mp[np.asarray(raw[:,t],np.int32)]
            score[st:en]=_positive_probability(self.model,xx)
            if progress: print(f'[{label}] {en:,}/{N:,}')
        if np.any(leaves<=0): raise RuntimeError('Non-leaf/padding id emitted by fitted tree encoder')
        return TreeArrays(leaves,score)

    def feature_importance_rows(self,names,top=40):
        imp=np.asarray(self.meta.feature_importance,float); order=np.argsort(-imp)[:int(top)]
        return [{'rank':r+1,'feature':str(names[int(i)]),'importance':float(imp[int(i)])} for r,i in enumerate(order)]

    def summary(self):
        m=self.meta
        return {'n_trees':int(m.n_trees),'leaf_vocab_size':int(m.vocab_size),'mean_leaves_per_tree':float(m.tree_leaf_counts.mean()),'min_leaves_per_tree':int(m.tree_leaf_counts.min()),'max_leaves_per_tree':int(m.tree_leaf_counts.max()),'training_oob_ap':self.oob_ap_}
