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

def _mlp(inp,hid,out,drop=.1):return nn.Sequential(nn.Linear(inp,hid),nn.LayerNorm(hid),nn.GELU(),nn.Dropout(drop),nn.Linear(hid,out))
def _logit(p):p=p.clamp(1e-5,1-1e-5);return torch.log(p)-torch.log1p(-p)

class CommitteePreservingGlobalExpert(nn.Module):
    def __init__(self,flat_dim,context_dim,n_faculties,d_model=64,faculty_dim=8,residual_bound=2.5,dropout=.1):
        super().__init__();self.fac=nn.Embedding(n_faculties,faculty_dim);self.residual_bound=float(residual_bound)
        self.backbone=nn.Sequential(nn.Linear(flat_dim+context_dim+faculty_dim,2*d_model),nn.LayerNorm(2*d_model),nn.GELU(),nn.Dropout(dropout),nn.Linear(2*d_model,d_model),nn.LayerNorm(d_model),nn.GELU())
        self.teacher_branch=_mlp(10,d_model,d_model,dropout);self.fuse=nn.Sequential(nn.Linear(2*d_model,d_model),nn.LayerNorm(d_model),nn.GELU());self.residual=nn.Linear(d_model,1);self.teacher_recon=nn.Linear(d_model,3);self.skip_norm=nn.LayerNorm(d_model)
        skip=torch.zeros(10,d_model);n=min(10,d_model);skip[:n,:n]=torch.eye(n);self.register_buffer('teacher_skip_matrix',skip)
        nn.init.zeros_(self.residual.weight);nn.init.zeros_(self.residual.bias)
    def teacher_features(self,p):
        p=p.clamp(1e-5,1-1e-5);q=p.mean(1,keepdim=True);lg=_logit(p);std=p.std(1,keepdim=True,unbiased=False);spread=(p.max(1,keepdim=True).values-p.min(1,keepdim=True).values);ent=-(q*torch.log(q)+(1-q)*torch.log(1-q));return torch.cat([p,lg,q,std,spread,ent],1)
    def forward(self,flat,context,faculty,committee_probs):
        features=self.teacher_features(committee_probs);neural=self.backbone(torch.cat([flat,context,self.fac(faculty)],1));te=self.teacher_branch(features);learned=self.fuse(torch.cat([neural,te],1));skip=features@self.teacher_skip_matrix;h=self.skip_norm(learned+skip);raw=self.residual(h).squeeze(1)
        delta=self.residual_bound*torch.tanh(raw/max(self.residual_bound,1e-6)) if self.residual_bound>0 else raw;q=committee_probs.mean(1).clamp(1e-5,1-1e-5);logit=_logit(q)+delta
        return h,logit,self.teacher_recon(h),delta

class StudentTrajectoryExpert(nn.Module):
    def __init__(self,input_dim,context_dim,n_faculties,d_model,faculty_dim=8,dropout=.1):
        super().__init__();self.inp=nn.Linear(input_dim,d_model);self.gru=nn.GRU(d_model,d_model,batch_first=True);self.query=nn.Linear(d_model,1);self.fac=nn.Embedding(n_faculties,faculty_dim);self.ctx=_mlp(context_dim+faculty_dim,d_model,d_model,dropout);self.out=nn.Sequential(nn.Linear(2*d_model,d_model),nn.LayerNorm(d_model),nn.GELU())
    def forward(self,x,mask,context,faculty):
        z,_=self.gru(self.inp(x));score=self.query(torch.tanh(z)).squeeze(-1).masked_fill(~mask,-1e4);a=torch.softmax(score,1)*mask.float();a=a/(a.sum(1,keepdim=True)+1e-6);h=(z*a.unsqueeze(-1)).sum(1);c=self.ctx(torch.cat([context,self.fac(faculty)],1));return self.out(torch.cat([h,c],1))
class CourseCurriculumExpert(nn.Module):
    def __init__(self,input_dim,context_dim,d_model,relation_types=13,dropout=.1):
        super().__init__();self.node=_mlp(input_dim,d_model,d_model,dropout);self.rel=nn.Embedding(relation_types,d_model);self.att=nn.Linear(2*d_model,1);self.ctx=_mlp(context_dim,d_model,d_model,dropout);self.out=nn.Sequential(nn.Linear(3*d_model,d_model),nn.LayerNorm(d_model),nn.GELU())
    def forward(self,target,neighbors,mask,rel_type,context):
        t=self.node(target);n=self.node(neighbors)+self.rel(rel_type.clamp(0,self.rel.num_embeddings-1));score=self.att(torch.cat([t[:,None,:].expand_as(n),n],-1)).squeeze(-1).masked_fill(~mask,-1e4);a=torch.softmax(score,1)*mask.float();a=a/(a.sum(1,keepdim=True)+1e-6);agg=(n*a.unsqueeze(-1)).sum(1);return self.out(torch.cat([t,agg,self.ctx(context)],1))
class CompatibilityExpert(nn.Module):
    def __init__(self,event_dim,course_dim,context_dim,n_faculties,d_model,faculty_dim=8,relation_types=14,dropout=.1):
        super().__init__();self.event=_mlp(event_dim,d_model,d_model,dropout);self.target=_mlp(course_dim,d_model,d_model,dropout);self.rel=nn.Embedding(relation_types,d_model);self.q=nn.Linear(d_model,d_model);self.k=nn.Linear(d_model,d_model);self.fac=nn.Embedding(n_faculties,faculty_dim);self.ctx=_mlp(context_dim+faculty_dim,d_model,d_model,dropout);self.out=nn.Sequential(nn.Linear(4*d_model,d_model),nn.LayerNorm(d_model),nn.GELU())
    def forward(self,events,mask,rel_type,target_course,context,faculty):
        e=self.event(events)+self.rel(rel_type.clamp(0,self.rel.num_embeddings-1));t=self.target(target_course);sc=(self.k(e)*self.q(t)[:,None,:]).sum(-1)/math.sqrt(e.shape[-1]);sc=sc.masked_fill(~mask,-1e4);a=torch.softmax(sc,1)*mask.float();a=a/(a.sum(1,keepdim=True)+1e-6);hist=(e*a.unsqueeze(-1)).sum(1);return self.out(torch.cat([t,hist,t*hist+torch.abs(t-hist),self.ctx(torch.cat([context,self.fac(faculty)],1))],1))
class MasteryEventExpert(nn.Module):
    def __init__(self,numeric_dim,context_dim,n_faculties,n_component_types,d_model,faculty_dim=8,type_dim=12,dropout=.1):
        super().__init__();self.typ=nn.Embedding(n_component_types,type_dim);self.event=_mlp(numeric_dim+type_dim,d_model,d_model,dropout);self.query=nn.Parameter(torch.randn(d_model)*.02);self.fac=nn.Embedding(n_faculties,faculty_dim);self.ctx=_mlp(context_dim+faculty_dim,d_model,d_model,dropout);self.out=nn.Sequential(nn.Linear(2*d_model,d_model),nn.LayerNorm(d_model),nn.GELU())
    def forward(self,events,mask,typ,context,faculty):
        e=self.event(torch.cat([events,self.typ(typ.clamp(0,self.typ.num_embeddings-1))],-1));sc=(e*self.query).sum(-1)/math.sqrt(e.shape[-1]);sc=sc.masked_fill(~mask,-1e4);a=torch.softmax(sc,1)*mask.float();a=a/(a.sum(1,keepdim=True)+1e-6);h=(e*a.unsqueeze(-1)).sum(1);return self.out(torch.cat([h,self.ctx(torch.cat([context,self.fac(faculty)],1))],1))
class EvidenceExchange(nn.Module):
    def __init__(self,d_model,n_experts=5,heads=4,dropout=.1):
        super().__init__();heads=max(1,min(heads,d_model));
        while d_model%heads:heads-=1
        self.types=nn.Embedding(n_experts,d_model);self.attn=nn.MultiheadAttention(d_model,heads,dropout=dropout,batch_first=True);self.gamma=nn.Parameter(torch.full((n_experts,),-2.0));self.norm=nn.LayerNorm(d_model);self.proj=nn.Linear(3*d_model,d_model)
    def forward(self,h,availability):
        k=h.shape[1];x=h+self.types(torch.arange(k,device=h.device))[None,:,:];msg,att=self.attn(x,x,x,key_padding_mask=~availability,need_weights=True,average_attn_weights=False);mixed=self.norm(h+torch.sigmoid(self.gamma)[None,:,None]*msg);tok=self.norm(self.proj(torch.cat([h,msg,h-msg],-1))+mixed);return tok*availability.unsqueeze(-1).float(),att

def apply_authority(e0_logit, collab_delta_logit, row_authority, authority_scale):
    """Apply an external deployment authority. authority_scale=0 is exact E0 identity."""
    if not torch.is_tensor(authority_scale):
        authority_scale=torch.as_tensor(authority_scale,dtype=e0_logit.dtype,device=e0_logit.device)
    return e0_logit + authority_scale * row_authority * collab_delta_logit


def local_competence_features(private_logits, availability):
    """Observable rowwise evidence for trust control; no target labels or absolute time."""
    p=torch.sigmoid(private_logits)
    disagreement=torch.abs(p[:,1:]-p[:,:1])
    confidence=torch.abs(p-.5)*2.0
    return torch.cat([p,disagreement,confidence,availability.float()],1)


class AuthoritySafeCollaborativeMoE(nn.Module):
    """Suite14: E0 identity plus an optional bounded collaborative correction.

    The collaborative branch can be disabled exactly by external authority_scale=0.
    Internally, the correction head is zero-initialized so the untrained model is also
    exact E0 identity. Row authority and expert routing see only observable evidence.
    """
    LOCAL_COMPETENCE_DIM=19
    def __init__(self,flat_dim,e0_context_dim,gate_context_dim,fusion_context_dim,e1_context_dim,e2_context_dim,e3_context_dim,e4_context_dim,student_dim,course_dim,relation_dim,component_numeric_dim,n_faculties,n_component_types,d_model=64,dropout=.1,e0_dropout=.15,expert_dropout=.05,e0_residual_bound=2.5,gate_faculty_dim=8,collab_delta_bound=2.0,authority_bias=-1.5):
        super().__init__();self.e0_dropout=float(e0_dropout);self.expert_dropout=float(expert_dropout);self.collab_delta_bound=float(collab_delta_bound)
        self.e0=CommitteePreservingGlobalExpert(flat_dim,e0_context_dim,n_faculties,d_model,residual_bound=e0_residual_bound,dropout=dropout)
        self.e1=StudentTrajectoryExpert(student_dim,e1_context_dim,n_faculties,d_model,dropout=dropout)
        self.e2=CourseCurriculumExpert(course_dim,e2_context_dim,d_model,dropout=dropout)
        self.e3=CompatibilityExpert(relation_dim,course_dim,e3_context_dim,n_faculties,d_model,dropout=dropout)
        self.e4=MasteryEventExpert(component_numeric_dim,e4_context_dim,n_faculties,n_component_types,d_model,dropout=dropout)
        self.private_heads=nn.ModuleList([nn.Identity()]+[nn.Linear(d_model,1) for _ in range(4)])
        self.mechanism_heads=nn.ModuleList([nn.Linear(d_model,1) for _ in range(4)])
        self.exchange=EvidenceExchange(d_model,5,4,dropout)
        self.gate_fac=nn.Embedding(n_faculties,gate_faculty_dim)
        gate_in=5*d_model+gate_context_dim+gate_faculty_dim+self.LOCAL_COMPETENCE_DIM
        self.gate=nn.Sequential(nn.Linear(gate_in,2*d_model),nn.GELU(),nn.Dropout(dropout),nn.Linear(2*d_model,5))
        self.value=nn.ModuleList([nn.Linear(d_model,d_model) for _ in range(5)])
        correction_in=d_model+d_model+fusion_context_dim+self.LOCAL_COMPETENCE_DIM
        self.correction=nn.Sequential(nn.Linear(correction_in,d_model),nn.LayerNorm(d_model),nn.GELU(),nn.Dropout(dropout),nn.Linear(d_model,1))
        authority_in=gate_context_dim+gate_faculty_dim+self.LOCAL_COMPETENCE_DIM+d_model
        self.authority=nn.Sequential(nn.Linear(authority_in,d_model),nn.GELU(),nn.Dropout(dropout),nn.Linear(d_model,1))
        # Exact no-op collaboration at initialization.
        nn.init.zeros_(self.correction[-1].weight);nn.init.zeros_(self.correction[-1].bias)
        nn.init.zeros_(self.authority[-1].weight);nn.init.constant_(self.authority[-1].bias,float(authority_bias))
    def _availability(self,b,device,student_mask,relation_mask,component_mask):
        a=torch.ones(b,5,dtype=torch.bool,device=device);a[:,1]=student_mask.any(1);a[:,2]=True;a[:,3]=relation_mask.any(1);a[:,4]=component_mask.any(1);base=a.clone()
        if self.training:
            # E0 can be removed from exchange, but never from the identity anchor l0.
            if self.e0_dropout>0:a[:,0]&=(torch.rand(b,device=device)>=self.e0_dropout)
            if self.expert_dropout>0:a[:,1:]&=~(torch.rand(b,4,device=device)<self.expert_dropout)
            dead=~a.any(1);a[dead,0]=True
        return a,base
    def forward(self,flat,e0_context,gate_context,fusion_context,e1_context,e2_context,e3_context,e4_context,faculty,committee_probs,student_seq,student_mask,course_target,course_neighbors,course_neighbor_mask,course_relation_type,relation_events,relation_mask,relation_type,component_events,component_mask,component_type,force_expert_off=None):
        h0,l0,teacher,e0_delta=self.e0(flat,e0_context,faculty,committee_probs)
        h1=self.e1(student_seq,student_mask,e1_context,faculty);h2=self.e2(course_target,course_neighbors,course_neighbor_mask,course_relation_type,e2_context)
        h3=self.e3(relation_events,relation_mask,relation_type,course_target,e3_context,faculty);h4=self.e4(component_events,component_mask,component_type,e4_context,faculty)
        h=torch.stack([h0,h1,h2,h3,h4],1)
        priv=torch.stack([l0]+[self.private_heads[i](h[:,i,:]).squeeze(1) for i in range(1,5)],1)
        mech=torch.stack([self.mechanism_heads[i](h[:,i+1,:]).squeeze(1) for i in range(4)],1)
        avail,base=self._availability(len(flat),flat.device,student_mask,relation_mask,component_mask)
        if force_expert_off is not None:
            j=int(force_expert_off);avail[:,j]=False;base[:,j]=False;dead=~avail.any(1);avail[dead,0]=True
        local=local_competence_features(priv,base)
        tok,att=self.exchange(h,avail)
        gate_input=torch.cat([tok.reshape(len(flat),-1),gate_context,self.gate_fac(faculty),local],1)
        gl=self.gate(gate_input).masked_fill(~avail,-1e4);w=torch.softmax(gl,1)
        vals=torch.stack([self.value[i](tok[:,i]) for i in range(5)],1);fused=(vals*w.unsqueeze(-1)).sum(1)
        raw_delta=self.correction(torch.cat([fused,h0,fusion_context,local],1)).squeeze(1)
        if self.collab_delta_bound>0:
            delta=self.collab_delta_bound*torch.tanh(raw_delta/max(self.collab_delta_bound,1e-6))
        else:delta=raw_delta
        row_authority=torch.sigmoid(self.authority(torch.cat([gate_context,self.gate_fac(faculty),local,fused],1)).squeeze(1))
        full=apply_authority(l0,delta,row_authority,1.0)
        return {'final_logit':full,'full_collab_logit':full,'private_logits':priv,'mechanism_logits':mech,'teacher_logits':teacher,'e0_delta_logit':e0_delta,'committee_probability':committee_probs.mean(1),'gate_weights':w,'expert_tokens':h,'collaborative_tokens':tok,'attention':att,'availability':avail,'base_availability':base,'local_competence':local,'collab_delta_logit':delta,'row_authority':row_authority,'e0_logit':l0}

# Explicit alias for downstream code that used the Suite13 class name.
CollaborativeEvidenceMoE=AuthoritySafeCollaborativeMoE
