# -*- coding: utf-8 -*-
from __future__ import annotations
import math
import torch
from torch import nn

class StraightThroughTreeEnsemble(nn.Module):
    """Self-contained GRANDE-style hard axis-aligned ensemble.

    Forward routing is hard. Feature choice and split decisions use straight-through
    estimators so gradients reach feature logits and thresholds.  Leaf-specific
    weight logits provide instance-wise estimator weighting. This is inspired by
    GRANDE/GradTree but is intentionally a compact research implementation, not a
    vendored copy of the official package.
    """
    def __init__(self,input_dim,n_estimators=128,depth=4,selected_variables=.8,split_temperature=.5,feature_temperature=.5,correction_bound=3.,seed=0):
        super().__init__(); self.input_dim=int(input_dim); self.n_estimators=int(n_estimators); self.depth=int(depth); self.n_nodes=2**self.depth-1; self.n_leaves=2**self.depth; self.split_temperature=float(split_temperature); self.feature_temperature=float(feature_temperature); self.correction_bound=float(correction_bound)
        g=torch.Generator();g.manual_seed(int(seed))
        self.feature_logits=nn.Parameter(torch.randn(self.n_estimators,self.n_nodes,self.input_dim,generator=g)*.02)
        self.thresholds=nn.Parameter(torch.zeros(self.n_estimators,self.n_nodes))
        self.leaf_values=nn.Parameter(torch.randn(self.n_estimators,self.n_leaves,generator=g)*.02)
        self.leaf_weight_logits=nn.Parameter(torch.zeros(self.n_estimators,self.n_leaves))
        keep=max(1,min(self.input_dim,int(round(float(selected_variables)*self.input_dim))))
        mask=torch.zeros(self.n_estimators,self.input_dim,dtype=torch.bool)
        for e in range(self.n_estimators):mask[e,torch.randperm(self.input_dim,generator=g)[:keep]]=True
        node_mask=mask[:,None,:].expand(-1,self.n_nodes,-1).clone();self.register_buffer('feature_mask',node_mask)
    def _selectors(self):
        logits=self.feature_logits.masked_fill(~self.feature_mask,-1e9); soft=torch.softmax(logits/max(self.feature_temperature,1e-3),dim=-1); idx=soft.argmax(-1); hard=torch.nn.functional.one_hot(idx,self.input_dim).to(soft.dtype); return hard-soft.detach()+soft
    def forward(self,x):
        x=x.float();sel=self._selectors(); chosen=torch.einsum('bf,enf->ben',x,sel)
        soft=torch.sigmoid((chosen-self.thresholds[None,:,:])/max(self.split_temperature,1e-3));hard=(soft>=.5).to(soft.dtype);dec=hard-soft.detach()+soft
        route=torch.ones((x.shape[0],self.n_estimators,1),device=x.device,dtype=x.dtype);offset=0
        for level in range(self.depth):
            n=2**level;d=dec[:,:,offset:offset+n];route=torch.stack([route*(1.-d),route*d],dim=-1).reshape(x.shape[0],self.n_estimators,n*2);offset+=n
        tree_out=(route*self.leaf_values[None,:,:]).sum(-1);weight_logits=(route*self.leaf_weight_logits[None,:,:]).sum(-1);weights=torch.softmax(weight_logits,dim=1);raw=(weights*tree_out).sum(1)
        return self.correction_bound*torch.tanh(raw/max(self.correction_bound,1e-6))

def model_feature_usage(model,feature_names=None,top_k=20):
    if model is None:return []
    with torch.no_grad():
        logits=model.feature_logits.masked_fill(~model.feature_mask,-1e9);idx=logits.argmax(-1).detach().cpu().numpy().reshape(-1)
    u,c=np.unique(idx,return_counts=True);order=np.argsort(-c);out=[]
    for j in order[:int(top_k)]:
        i=int(u[j]);out.append((feature_names[i] if feature_names and i<len(feature_names) else str(i),int(c[j])))
    return out
