# -*- coding: utf-8 -*-
from __future__ import annotations
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


class ResBlock(nn.Module):
    def __init__(self,d,dropout=.1,mult=2):
        super().__init__(); h=int(d*mult); self.norm=nn.LayerNorm(d)
        self.net=nn.Sequential(nn.Linear(d,h),nn.GELU(),nn.Dropout(dropout),nn.Linear(h,d),nn.Dropout(dropout))
    def forward(self,x): return x+self.net(self.norm(x))


class TreeLeafEncoder(nn.Module):
    def __init__(self,leaf_stats,n_trees,leaf_dim=16,state_dim=64,dropout=.05):
        super().__init__(); stats=torch.as_tensor(np.asarray(leaf_stats,np.float32)); self.register_buffer('leaf_stats',stats)
        self.n_trees=int(n_trees); self.leaf_emb=nn.Embedding(stats.shape[0],int(leaf_dim),padding_idx=0)
        self.stats_proj=nn.Linear(stats.shape[1],int(leaf_dim),bias=False); self.tree_logits=nn.Parameter(torch.zeros(self.n_trees))
        self.out=nn.Sequential(nn.LayerNorm(int(leaf_dim)),nn.Linear(int(leaf_dim),state_dim),nn.GELU(),nn.Dropout(dropout))
        nn.init.normal_(self.leaf_emb.weight,std=.02)
        with torch.no_grad(): self.leaf_emb.weight[0].zero_()
    def forward(self,leaf_ids,ablate=False):
        shape=leaf_ids.shape
        if shape[-1]!=self.n_trees: raise ValueError(f'leaf tree count {shape[-1]} != {self.n_trees}')
        flat=leaf_ids.reshape(-1,self.n_trees).long(); tok=self.leaf_emb(flat)+self.stats_proj(self.leaf_stats[flat])
        w=F.softmax(self.tree_logits,dim=0); pooled=(tok*w[None,:,None]).sum(1)
        out=self.out(pooled).reshape(*shape[:-1],-1)
        return torch.zeros_like(out) if ablate else out


def _logit_tensor(p):
    p=p.clamp(1e-5,1-1e-5); return torch.log(p)-torch.log1p(-p)


class TreeNativeAcademicMemory(nn.Module):
    """Suite26 unified tree-native current-state + episodic-memory framework.

    Variants
    --------
    memory : Tree-native current state + target-conditioned student memory.
    tair   : PRIMARY. Adds latent multidimensional student ability / target-course
             requirement interaction (TAIR = Tree + Academic-memory + IRT-like Relation).

    The tree forest is internal to the Suite26 pipeline and is *not* the Committee.
    A zero-initialized bounded interaction correction preserves the single-tree baseline
    at initialization, while a jointly-trained unanchored head is exposed as a diagnostic.
    """
    def __init__(self,n_features,n_course_features,n_faculties,leaf_stats,n_trees,variant='tair',
                 state_dim=64,course_dim=32,memory_dim=64,ability_dim=16,leaf_dim=16,
                 faculty_dim=8,dropout=.10,delta_cap=2.0):
        super().__init__(); self.variant=str(variant); self.n_course=int(n_course_features); self.delta_cap=float(delta_cap); self.ability_dim=int(ability_dim); self.state_dim=int(state_dim); self.memory_dim=int(memory_dim)
        if self.state_dim!=self.memory_dim: raise ValueError('Suite26 currently requires state_dim == memory_dim for explicit interaction products')
        self.tree_encoder=TreeLeafEncoder(leaf_stats,n_trees,leaf_dim,state_dim,dropout/2)
        self.faculty_emb=nn.Embedding(int(n_faculties),int(faculty_dim))
        self.raw_proj=nn.Sequential(nn.Linear(int(n_features),128),nn.GELU(),nn.Dropout(dropout),nn.Linear(128,state_dim),nn.LayerNorm(state_dim))
        self.course_encoder=nn.Sequential(nn.Linear(self.n_course,64),nn.GELU(),nn.Dropout(dropout),nn.Linear(64,course_dim),nn.LayerNorm(course_dim))
        self.current_fuse=nn.Sequential(nn.Linear(state_dim+state_dim+1+faculty_dim,state_dim),nn.GELU(),nn.Dropout(dropout),ResBlock(state_dim,dropout))
        key_dim=64
        self.query_key=nn.Sequential(nn.Linear(state_dim+course_dim,key_dim),nn.GELU(),nn.Linear(key_dim,key_dim))
        self.hist_key=nn.Sequential(nn.Linear(state_dim+course_dim,key_dim),nn.GELU(),nn.Linear(key_dim,key_dim))
        # recency features + same-course produce a relevance bias. Outcomes never enter keys.
        self.att_bias=nn.Sequential(nn.Linear(3,16),nn.Tanh(),nn.Linear(16,1,bias=False)); nn.init.zeros_(self.att_bias[-1].weight)
        value_in=state_dim+course_dim+1+1+1+2+1 # hist state, course, y, grade, present, recency2, hist tree logit
        self.value_net=nn.Sequential(nn.Linear(value_in,128),nn.GELU(),nn.Dropout(dropout),nn.Linear(128,memory_dim),nn.LayerNorm(memory_dim))
        ability_in=state_dim+course_dim+1+1+1+2
        self.ability_event=nn.Sequential(nn.Linear(ability_in,64),nn.GELU(),nn.Linear(64,ability_dim),nn.Tanh())
        self.requirement=nn.Sequential(nn.Linear(course_dim,ability_dim),nn.Tanh())
        self.discrimination=nn.Linear(course_dim,ability_dim); self.difficulty=nn.Linear(course_dim,1)
        support_dim=7
        # Interaction is explicitly non-additive before the correction head.
        inter_dim=state_dim+memory_dim+course_dim+ability_dim+ability_dim+state_dim+state_dim+ability_dim+1+1+support_dim
        self.interaction=nn.Sequential(nn.Linear(inter_dim,256),nn.GELU(),nn.Dropout(dropout),ResBlock(256,dropout),nn.Linear(256,128),nn.GELU(),nn.Dropout(dropout))
        # The tree-preserving correction is intentionally memory-dependent. It does
        # not get a free standalone current-state branch; otherwise B-A would mix a
        # neural current-state correction with the episodic-memory hypothesis.
        delta_in=memory_dim+state_dim+ability_dim+ability_dim+1+support_dim
        self.delta_interaction=nn.Sequential(nn.Linear(delta_in,128,bias=False),nn.GELU(),nn.Dropout(dropout),nn.Linear(128,128),nn.GELU())
        self.delta_head=nn.Linear(128,1); nn.init.zeros_(self.delta_head.weight); nn.init.zeros_(self.delta_head.bias)
        self.joint_head=nn.Sequential(nn.Linear(128,64),nn.GELU(),nn.Linear(64,1))

    def _current_state(self,current,leaf,tree_score,faculty,ablate_leaf=False):
        leaf_state=self.tree_encoder(leaf,ablate_leaf); raw=self.raw_proj(current.float()); tl=_logit_tensor(tree_score.float()).unsqueeze(-1); fe=self.faculty_emb(faculty.long())
        state=self.current_fuse(torch.cat([leaf_state,raw,tl,fe],-1)); return state,leaf_state,raw

    def _history(self,b,current_state,target_course,ablate):
        mask=b['history_mask'].bool(); B,H=mask.shape
        if H==0 or 'no_memory' in ablate:
            zero=current_state.new_zeros((B,self.memory_dim)); theta=current_state.new_zeros((B,self.ability_dim)); att=current_state.new_zeros((B,H)); support=current_state.new_zeros((B,7))
            return zero,theta,att,support
        hx=b['history_x'].float(); hleaf=b['history_leaf']; hts=b['history_tree_score'].float();
        flat_x=hx.reshape(B*H,-1); flat_leaf=hleaf.reshape(B*H,hleaf.shape[-1]); flat_score=hts.reshape(B*H)
        # Historical leaf and raw state share the same encoders; no faculty embedding is needed
        # here because the history belongs to the same student/faculty as the query.
        hleaf_state=self.tree_encoder(flat_leaf,'no_tree_leaf' in ablate).reshape(B,H,-1)
        hraw=self.raw_proj(flat_x).reshape(B,H,-1); hlog=_logit_tensor(flat_score).reshape(B,H,1)
        # Fuse historical tree/raw states without faculty to avoid repeating a constant token.
        # Reuse a simple average; both are 64-d and already normalized/projected.
        hstate=0.5*(hleaf_state+hraw)
        hcourse=self.course_encoder(hx[...,-self.n_course:])
        q=self.query_key(torch.cat([current_state,target_course],-1)); k=self.hist_key(torch.cat([hstate,hcourse],-1))
        rec=torch.clamp(b['history_recency'].float(),min=0.); r1=torch.log1p(rec)/3.; r2=torch.exp(-rec/3.)
        if 'no_recency' in ablate: r1=torch.zeros_like(r1); r2=torch.zeros_like(r2)
        sc=b['history_same_course'].float();
        if 'no_same_course_bias' in ablate: sc=torch.zeros_like(sc)
        bias=self.att_bias(torch.stack([r1,r2,sc],-1)).squeeze(-1)
        score=(q[:,None,:]*k).sum(-1)/math.sqrt(float(k.shape[-1]))+bias
        score=score.masked_fill(~mask,-1e9); none=~mask.any(1)
        if 'uniform_attention' in ablate: score=torch.zeros_like(score).masked_fill(~mask,-1e9)
        if torch.any(none): score=score.clone(); score[none]=0.
        att=F.softmax(score,dim=-1); att=torch.where(mask,att,torch.zeros_like(att)); att=torch.where(none[:,None],torch.zeros_like(att),att)
        yy=b['history_y'].float(); grade=b['history_grade'].float(); present=b['history_grade_present'].float()
        if 'no_labels' in ablate: yy=torch.zeros_like(yy)
        if 'no_grades' in ablate: grade=torch.full_like(grade,.5); present=torch.zeros_like(present)
        grade_center=(grade-.5)*2
        val_in=torch.cat([hstate,hcourse,yy.unsqueeze(-1),grade_center.unsqueeze(-1),present.unsqueeze(-1),r1.unsqueeze(-1),r2.unsqueeze(-1),hlog],-1)
        values=self.value_net(val_in); memory=(att.unsqueeze(-1)*values).sum(1)
        ability_in=torch.cat([hstate,hcourse,yy.unsqueeze(-1),grade_center.unsqueeze(-1),present.unsqueeze(-1),r1.unsqueeze(-1),r2.unsqueeze(-1)],-1)
        ev=self.ability_event(ability_in); theta=(att.unsqueeze(-1)*ev).sum(1)
        count=mask.sum(1).float(); den=count.clamp(min=1.)
        raw_fail=(yy*mask).sum(1)/den; raw_grade=(grade*present*mask).sum(1)/(present*mask).sum(1).clamp(min=1.)
        wfail=(att*yy).sum(1); wgrade=(att*grade).sum(1)
        top1=att.max(1).values; ent=-(att.clamp(min=1e-8)*torch.log(att.clamp(min=1e-8))).sum(1)/torch.log(den.clamp(min=2.)); same_mass=(att*sc).sum(1)
        support=torch.stack([torch.log1p(count)/3.,raw_fail,raw_grade,wfail,wgrade,top1,same_mass],-1)
        return memory,theta,att,support

    def forward(self,b,return_aux=False,ablate=None):
        abl=set(ablate or []); current=b['current'].float(); tree_score=b['tree_score'].float().clamp(1e-5,1-1e-5)
        state,leaf_state,raw_state=self._current_state(current,b['current_leaf'],tree_score,b['faculty_idx'],'no_tree_leaf' in abl)
        target_course=self.course_encoder(current[...,-self.n_course:])
        memory,theta,att,support=self._history(b,state,target_course,abl)
        use_ability=(self.variant=='tair' and 'no_ability' not in abl and 'no_memory' not in abl)
        if use_ability:
            req=self.requirement(target_course); disc=F.softplus(self.discrimination(target_course))+0.05; diff=self.difficulty(target_course).squeeze(-1)
            zability=(disc*(theta-req)).sum(-1)/math.sqrt(float(self.ability_dim))-diff; zability=torch.clamp(zability,-8,8)
        else:
            req=torch.zeros((len(state),self.ability_dim),device=state.device,dtype=state.dtype); theta=torch.zeros_like(req) if self.variant!='tair' or 'no_ability' in abl else theta; zability=torch.zeros(len(state),device=state.device,dtype=state.dtype)
        inter=torch.cat([state,memory,target_course,theta,req,state*memory,torch.abs(state-memory),theta*req,zability.unsqueeze(-1),_logit_tensor(tree_score).unsqueeze(-1),support],-1)
        h=self.interaction(inter); joint=self.joint_head(h).squeeze(-1)
        dh=self.delta_interaction(torch.cat([memory,state*memory,theta,theta*req,zability.unsqueeze(-1),support],-1))
        has_history=b['history_mask'].bool().any(1).float();
        if 'no_memory' in abl: has_history=torch.zeros_like(has_history)
        delta=self.delta_cap*torch.tanh(self.delta_head(dh).squeeze(-1))*has_history; tree_logit=_logit_tensor(tree_score)
        primary=tree_logit+delta
        if 'tree_only' in abl: primary=tree_logit
        if not return_aux: return primary
        return primary,{'joint_logit':joint,'delta':delta,'tree_logit':tree_logit,'attention':att,'memory':memory,'theta':theta,'requirement':req,'ability_logit':zability,'support_features':support,'leaf_state':leaf_state,'raw_state':raw_state,'history_available':has_history}
