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

class QueryPool(nn.Module):
    def __init__(self,d_model=64,heads=4,dropout=.1):
        super().__init__();self.attn=nn.MultiheadAttention(d_model,heads,dropout=dropout,batch_first=True);self.norm=nn.LayerNorm(d_model)
    def forward(self,q,x,mask):
        # q [B,D], x [B,K,D], mask True for valid
        if x.shape[1]==0:return torch.zeros_like(q),torch.zeros((len(q),0),device=q.device)
        mask=mask.bool();valid=mask.any(1);safe_mask=mask.clone()
        if torch.any(~valid):safe_mask[~valid,0]=True
        key_padding=~safe_mask;out,w=self.attn(q[:,None,:],x,x,key_padding_mask=key_padding,need_weights=True,average_attn_weights=True)
        out=out[:,0,:];out=torch.where(valid[:,None],out,torch.zeros_like(out));w=w[:,0,:];w=torch.where(mask,w,torch.zeros_like(w));return self.norm(out),w

class PositiveGate(nn.Module):
    """Very low-capacity monotone evidence gate. More available/relevant evidence cannot lower authority."""
    def __init__(self,n_features,bias=-1.5):
        super().__init__();self.raw_weight=nn.Parameter(torch.zeros(n_features));self.bias=nn.Parameter(torch.tensor(float(bias)))
    def forward(self,x):return torch.sigmoid(self.bias+(F.softplus(self.raw_weight)*x).sum(-1))

class TargetConditionedStructuralResidual(nn.Module):
    """Suite24 model.

    variant='history': student-history correction only, fixed bounded authority.
    variant='structural': history + direct course-structure corrections, fixed bounded authority.
    variant='evidence': same two corrections with monotone row-wise evidence-conditioned gates.

    The primary prediction is Committee-anchored. An auxiliary standalone head is trained jointly
    so the experiment also measures how much of the task the relational architecture can solve without Committee.
    """
    def __init__(self,variant='evidence',d_model=64,heads=4,dropout=.1,student_mean=None,student_std=None,course_mean=None,course_std=None,delta_cap=.75):
        super().__init__();self.variant=str(variant);self.d=d_model;self.delta_cap=float(delta_cap)
        self.student_enc=nn.Sequential(nn.Linear(STUDENT_RAW_DIM,d_model),nn.GELU(),nn.LayerNorm(d_model))
        self.course_enc=nn.Sequential(nn.Linear(COURSE_RAW_DIM,d_model),nn.GELU(),nn.LayerNorm(d_model))
        self.edge_enc=nn.Sequential(nn.Linear(EDGE_RAW_DIM,d_model),nn.GELU(),nn.Linear(d_model,d_model))
        self.rel_emb=nn.Embedding(14,d_model)
        self.pair_proj=nn.Sequential(nn.Linear(4*d_model,d_model),nn.GELU(),nn.LayerNorm(d_model))
        self.hist_token_norm=nn.LayerNorm(d_model);self.struct_token_norm=nn.LayerNorm(d_model)
        self.hist_pool=QueryPool(d_model,heads,dropout);self.struct_pool=QueryPool(d_model,heads,dropout)
        self.hist_delta=nn.Sequential(nn.Linear(3*d_model+6,128),nn.GELU(),nn.Dropout(dropout),nn.Linear(128,1))
        self.struct_delta=nn.Sequential(nn.Linear(4*d_model+6,128),nn.GELU(),nn.Dropout(dropout),nn.Linear(128,1))
        self.hist_gate=PositiveGate(4,-1.0);self.struct_gate=PositiveGate(3,-1.5)
        stand_dim=6*d_model+6
        self.standalone=nn.Sequential(nn.Linear(stand_dim,256),nn.GELU(),nn.Dropout(dropout),nn.Linear(256,64),nn.GELU(),nn.Dropout(dropout),nn.Linear(64,1))
        sm=torch.zeros(STUDENT_RAW_DIM) if student_mean is None else torch.as_tensor(student_mean,dtype=torch.float32);ss=torch.ones(STUDENT_RAW_DIM) if student_std is None else torch.as_tensor(student_std,dtype=torch.float32)
        cm=torch.zeros(COURSE_RAW_DIM) if course_mean is None else torch.as_tensor(course_mean,dtype=torch.float32);cs=torch.ones(COURSE_RAW_DIM) if course_std is None else torch.as_tensor(course_std,dtype=torch.float32)
        self.register_buffer('student_mean',sm);self.register_buffer('student_std',ss.clamp_min(1e-3));self.register_buffer('course_mean',cm);self.register_buffer('course_std',cs.clamp_min(1e-3))

    def _course(self,x):return self.course_enc((x.float()-self.course_mean)/(self.course_std+1e-6))
    def _student(self,x):return self.student_enc((x.float()-self.student_mean)/(self.student_std+1e-6))
    @staticmethod
    def _committee_logit(p):
        p=p.float().clamp(1e-6,1-1e-6);return torch.log(p)-torch.log1p(-p)

    def forward(self,batch,return_aux=False,ablate=None):
        abl=set(ablate or []);s=self._student(batch['student_x']);c=self._course(batch['target_course_x']);q=self.pair_proj(torch.cat([s,c,s*c,torch.abs(s-c)],-1))
        hx=self._course(batch['history_x']);he=self.edge_enc(batch['history_edge'].float());hr=self.rel_emb(batch['history_rel'].long().clamp(0,13));ht=self.hist_token_norm(hx+he+hr);hm=batch['history_mask'].bool()
        if 'history' in abl:hm=torch.zeros_like(hm)
        rh,wh=self.hist_pool(q,ht,hm)
        sx=self._course(batch['struct_x']);se=self.edge_enc(batch['struct_edge'].float());sr=self.rel_emb(batch['struct_rel'].long().clamp(0,13));st=self.struct_token_norm(sx+se+sr);sm=batch['struct_mask'].bool()
        if self.variant=='history' or 'structural' in abl:sm=torch.zeros_like(sm)
        rs,ws=self.struct_pool(q,st,sm)
        support=batch['support'].float();sup=torch.stack([support[:,0]/MAX_HISTORY_COURSES,support[:,1]/MAX_STRUCT_COURSES,support[:,2]/MAX_HISTORY_COURSES,support[:,3]/MAX_HISTORY_COURSES,support[:,4]/MAX_HISTORY_COURSES,support[:,5]/MAX_STRUCT_COURSES],-1).clamp(0,1)
        dh_raw=self.hist_delta(torch.cat([s,c,rh,sup],-1)).squeeze(-1);ds_raw=self.struct_delta(torch.cat([s,c,rh,rs,sup],-1)).squeeze(-1)
        hist_avail=(support[:,0]>0).to(dh_raw.dtype);struct_avail=(support[:,1]>0).to(ds_raw.dtype)
        if self.variant=='evidence' and 'fixed_gates' not in abl:
            gh=self.hist_gate(sup[:,[0,2,3,4]])*hist_avail;gs=self.struct_gate(sup[:,[1,5,2]])*struct_avail
        else:
            gh=hist_avail;gs=struct_avail
        if 'history_gate' in abl or 'history_correction' in abl:gh=torch.zeros_like(gh)
        if self.variant=='history' or 'struct_gate' in abl or 'structural_correction' in abl:gs=torch.zeros_like(ds_raw)
        dh=self.delta_cap*torch.tanh(dh_raw)*gh;ds=self.delta_cap*torch.tanh(ds_raw)*gs
        corr=dh+ds;zc=self._committee_logit(batch['committee']);z=zc+corr
        stand_repr=torch.cat([s,c,s*c,torch.abs(s-c),rh,rs,sup],-1);z_ind=self.standalone(stand_repr).squeeze(-1)
        if not return_aux:return z
        return z,{'standalone_logit':z_ind,'correction':corr,'history_correction':dh,'structural_correction':ds,'history_gate':gh,'structural_gate':gs,'history_attention':wh,'structural_attention':ws,'history_repr':rh,'structural_repr':rs}
