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


def segment_softmax(logits, dst, n_segments):
    """Softmax over incoming edges for every destination node and head."""
    if logits.numel()==0:return logits
    m,h=logits.shape; dev=logits.device
    idx=dst[:,None]*h+torch.arange(h,device=dev)[None,:]; idxf=idx.reshape(-1); val=logits.reshape(-1)
    mx=torch.full((n_segments*h,),-torch.inf,device=dev,dtype=val.dtype)
    mx.scatter_reduce_(0,idxf,val,reduce='amax',include_self=True)
    ex=torch.exp(val-mx[idxf]);den=torch.zeros_like(mx);den.scatter_add_(0,idxf,ex)
    return (ex/(den[idxf]+1e-12)).view(m,h)


class EdgeAwareHeteroLayer(nn.Module):
    def __init__(self,d_model=64,heads=4,n_rel=8,edge_dim=EDGE_RAW_DIM,dropout=.1):
        super().__init__();assert d_model%heads==0
        self.d=d_model;self.h=heads;self.dh=d_model//heads;self.n_rel=n_rel
        self.q=nn.ModuleList([nn.Identity()]+[nn.Linear(d_model,d_model,bias=False) for _ in range(n_rel)])
        self.k=nn.ModuleList([nn.Identity()]+[nn.Linear(d_model,d_model,bias=False) for _ in range(n_rel)])
        self.v=nn.ModuleList([nn.Identity()]+[nn.Linear(d_model,d_model,bias=False) for _ in range(n_rel)])
        self.ek=nn.ModuleList([nn.Identity()]+[nn.Linear(edge_dim,d_model,bias=False) for _ in range(n_rel)])
        self.ev=nn.ModuleList([nn.Identity()]+[nn.Linear(edge_dim,d_model,bias=False) for _ in range(n_rel)])
        self.bias=nn.Parameter(torch.zeros(n_rel+1,heads));self.out=nn.Linear(d_model,d_model);self.norm1=nn.LayerNorm(d_model);self.norm2=nn.LayerNorm(d_model);self.drop=nn.Dropout(dropout)
        self.ff=nn.Sequential(nn.Linear(d_model,2*d_model),nn.GELU(),nn.Dropout(dropout),nn.Linear(2*d_model,d_model))
    def forward(self,h,edge_src,edge_dst,edge_type,edge_attr,edge_mask,node_mask,allowed_rel=None,return_attention=False):
        B,N,D=h.shape;E=edge_src.shape[1];flat=h.reshape(B*N,D);out=torch.zeros_like(flat);attn_all=torch.zeros((B,E),device=h.device,dtype=h.dtype) if return_attention else None
        offsets=(torch.arange(B,device=h.device)*N)[:,None]
        srcg=(edge_src.long()+offsets).reshape(-1);dstg=(edge_dst.long()+offsets).reshape(-1);typ=edge_type.long().reshape(-1);valid=edge_mask.reshape(-1).bool();attrs=edge_attr.reshape(-1,edge_attr.shape[-1])
        if allowed_rel is not None:
            allow=torch.zeros(self.n_rel+1,dtype=torch.bool,device=h.device)
            for r in allowed_rel:
                if 0<=int(r)<=self.n_rel:allow[int(r)]=True
            valid &= allow[typ]
        for r in range(1,self.n_rel+1):
            m=valid&(typ==r)
            if not torch.any(m):continue
            s=srcg[m];d=dstg[m];ea=attrs[m]
            q=self.q[r](flat[d]).view(-1,self.h,self.dh);k=self.k[r](flat[s]).view(-1,self.h,self.dh)+self.ek[r](ea).view(-1,self.h,self.dh);v=self.v[r](flat[s]).view(-1,self.h,self.dh)+self.ev[r](ea).view(-1,self.h,self.dh)
            logits=(q*k).sum(-1)/math.sqrt(self.dh)+self.bias[r][None,:];a=segment_softmax(logits,d,B*N);msg=(a[...,None]*v).reshape(-1,D)
            out.index_add_(0,d,msg)
            if return_attention:
                pos=torch.where(m)[0];attn_all.view(-1)[pos]=a.mean(-1)
        out=self.out(out).view(B,N,D);h=self.norm1(h+self.drop(out));h=self.norm2(h+self.drop(self.ff(h)));h=h*node_mask[...,None].to(h.dtype)
        return h,attn_all


class QueryReadout(nn.Module):
    def __init__(self,d_model=64,d_att=64):
        super().__init__();self.q=nn.Linear(d_model,d_att,bias=False);self.k=nn.Linear(d_model,d_att,bias=False);self.v=nn.Linear(d_model,d_model,bias=False);self.scale=math.sqrt(d_att)
    def forward(self,query,items,mask):
        # query [B,D], items [B,K,D], mask [B,K]
        q=self.q(query)[:,None,:];k=self.k(items);scores=(q*k).sum(-1)/self.scale;scores=scores.masked_fill(~mask,-1e9);w=torch.softmax(scores,dim=1);w=torch.where(mask,w,torch.zeros_like(w));den=w.sum(1,keepdim=True);w=torch.where(den>0,w/(den+1e-12),w);out=torch.sum(w[...,None]*self.v(items),1);return out,w


class CSHAGT(nn.Module):
    """Chronology-Safe Heterogeneous Academic Graph Transformer.

    variant='bipartite': student-course interactions only, root-pair readout.
    variant='hetero': adds course relations, structural groups and faculty graph context.
    variant='full': adds relative-time edge features and dual target-conditioned readouts.
    """
    def __init__(self,variant='full',d_model=64,heads=4,layers=2,dropout=.1,n_faculties=14,node_mean=None,node_std=None):
        super().__init__();self.variant=str(variant);self.d=d_model;self.layers_n=layers
        self.type_proj=nn.ModuleList([nn.Identity()]+[nn.Sequential(nn.Linear(NODE_RAW_DIM,d_model),nn.GELU(),nn.LayerNorm(d_model)) for _ in range(4)])
        self.type_emb=nn.Embedding(5,d_model);self.faculty_emb=nn.Embedding(max(1,n_faculties),16);self.faculty_graph_emb=nn.Embedding(max(1,n_faculties),d_model)
        self.layers=nn.ModuleList([EdgeAwareHeteroLayer(d_model,heads,8,EDGE_RAW_DIM,dropout) for _ in range(layers)])
        self.hist_readout=QueryReadout(d_model);self.cohort_readout=QueryReadout(d_model)
        pair_dim=6*d_model+16+4
        self.head=nn.Sequential(nn.Linear(pair_dim,256),nn.GELU(),nn.Dropout(dropout),nn.Linear(256,64),nn.GELU(),nn.Dropout(dropout),nn.Linear(64,1))
        if node_mean is None:node_mean=torch.zeros((5,NODE_RAW_DIM),dtype=torch.float32)
        if node_std is None:node_std=torch.ones((5,NODE_RAW_DIM),dtype=torch.float32)
        self.register_buffer('node_mean',torch.as_tensor(node_mean,dtype=torch.float32));self.register_buffer('node_std',torch.as_tensor(node_std,dtype=torch.float32).clamp_min(1e-3))
    @property
    def allowed_relations(self):
        if self.variant=='bipartite':return {REL_STUDENT_TOOK,REL_COURSE_TAKEN_BY}
        return set(range(1,9))
    def _node_encode(self,x,typ,mask):
        x=(x-self.node_mean[typ])/(self.node_std[typ]+1e-6);out=torch.zeros((*x.shape[:-1],self.d),device=x.device,dtype=x.dtype)
        for t in range(1,5):
            m=(typ==t)&mask
            if torch.any(m):out[m]=self.type_proj[t](x[m])+self.type_emb.weight[t]
        return out*mask[...,None].to(x.dtype)
    def forward(self,batch,return_aux=False,ablate=None):
        ablate=set(ablate or []);x=batch['node_x'].float();typ=batch['node_type'].long();nmask=batch['node_mask'].bool();edge_attr=batch['edge_attr'].float().clone();etype=batch['edge_type'].long();emask=batch['edge_mask'].bool().clone()
        if self.variant!='full' or 'time' in ablate:edge_attr[...,3:5]=0
        if 'structural' in ablate:emask &= ~((etype==REL_COURSE_TO_RELATED)|(etype==REL_RELATED_TO_COURSE))
        if 'groups' in ablate:emask &= ~((etype==REL_COURSE_TO_GROUP)|(etype==REL_GROUP_TO_COURSE))
        if 'faculty_edges' in ablate:emask &= ~((etype==REL_ENTITY_TO_FACULTY)|(etype==REL_FACULTY_TO_ENTITY))
        fac=batch['faculty_idx'].long();h=self._node_encode(x,typ,nmask);h[:,SL_FACULTY]=self.faculty_graph_emb(fac);h=h*nmask[...,None].to(h.dtype);edge_att=None
        for li,layer in enumerate(self.layers):h,edge_att=layer(h,batch['edge_src'],batch['edge_dst'],etype,edge_attr,emask,nmask,self.allowed_relations,return_attention=return_aux and li==len(self.layers)-1)
        hs=h[:,SL_ROOT_STUDENT];hc=h[:,SL_ROOT_COURSE];hist=h[:,SL_HISTORY];coh=h[:,SL_COHORT];hist_m=nmask[:,SL_HISTORY];coh_m=nmask[:,SL_COHORT]
        if self.variant=='full' and 'student_history_readout' not in ablate:r_hist,wh=self.hist_readout(hc,hist,hist_m)
        else:r_hist=torch.zeros_like(hs);wh=torch.zeros(hist_m.shape,device=h.device,dtype=h.dtype)
        if self.variant=='full' and 'course_cohort_readout' not in ablate:r_coh,wc=self.cohort_readout(hs,coh,coh_m)
        else:r_coh=torch.zeros_like(hs);wc=torch.zeros(coh_m.shape,device=h.device,dtype=h.dtype)
        fe=self.faculty_emb(fac);support=batch['support'].float();support=support/torch.tensor([MAX_HISTORY_COURSES,MAX_COHORT_STUDENTS,MAX_STRUCT_COURSES,MAX_GROUPS],device=h.device,dtype=h.dtype)
        pair=torch.cat([hs,hc,hs*hc,torch.abs(hs-hc),r_hist,r_coh,fe,support],-1);logit=self.head(pair).squeeze(-1)
        if not return_aux:return logit
        return logit,{'edge_attention':edge_att,'history_attention':wh,'cohort_attention':wc,'student_repr':hs,'course_repr':hc}
