import os, sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT))
import numpy as np
import torch
from suite24_common import QueryBundle, sigmoid, logit
from suite24_graph_index import *
from suite24_model import TargetConditionedStructuralResidual


def batch(B=5):
    return {'student_x':torch.randn(B,STUDENT_RAW_DIM),'target_course_x':torch.randn(B,COURSE_RAW_DIM),'history_x':torch.randn(B,MAX_HISTORY_COURSES,COURSE_RAW_DIM),'history_edge':torch.randn(B,MAX_HISTORY_COURSES,EDGE_RAW_DIM),'history_rel':torch.randint(0,14,(B,MAX_HISTORY_COURSES)),'history_mask':torch.ones(B,MAX_HISTORY_COURSES,dtype=torch.bool),'struct_x':torch.randn(B,MAX_STRUCT_COURSES,COURSE_RAW_DIM),'struct_edge':torch.randn(B,MAX_STRUCT_COURSES,EDGE_RAW_DIM),'struct_rel':torch.randint(0,14,(B,MAX_STRUCT_COURSES)),'struct_mask':torch.ones(B,MAX_STRUCT_COURSES,dtype=torch.bool),'support':torch.tensor([[16,10,4,1,5,5]]*B,dtype=torch.float32),'committee':torch.linspace(.05,.8,B)}

def test_shapes_and_finite():
    b=batch();m=TargetConditionedStructuralResidual('evidence');z,a=m(b,return_aux=True);assert z.shape==(5,);assert a['standalone_logit'].shape==(5,);assert torch.isfinite(z).all();assert ((a['history_gate']>=0)&(a['history_gate']<=1)).all()

def test_history_variant_has_no_structural_correction():
    b=batch();m=TargetConditionedStructuralResidual('history');_,a=m(b,return_aux=True);assert torch.allclose(a['structural_correction'],torch.zeros_like(a['structural_correction']))

def test_zero_both_corrections_exact_committee_logit():
    b=batch();m=TargetConditionedStructuralResidual('evidence');z,_=m(b,return_aux=True,ablate=['history_correction','structural_correction']);q=b['committee'].clamp(1e-6,1-1e-6);expected=torch.log(q)-torch.log1p(-q);assert torch.allclose(z,expected,atol=1e-6)

def test_positive_gate_support_monotone():
    m=TargetConditionedStructuralResidual('evidence');g=m.hist_gate;x0=torch.zeros(1,4);x1=torch.ones(1,4);assert float(g(x1))>=float(g(x0))

def test_all_masked_attention_is_finite():
    b=batch(3);b['struct_mask'].zero_();b['support'][:,1]=0;b['support'][:,5]=0;m=TargetConditionedStructuralResidual('evidence');z,a=m(b,return_aux=True);assert torch.isfinite(z).all();assert torch.isfinite(a['structural_repr']).all()

def test_delta_is_bounded():
    b=batch();m=TargetConditionedStructuralResidual('structural',delta_cap=.75);_,a=m(b,return_aux=True);assert float(a['history_correction'].abs().max())<=.750001;assert float(a['structural_correction'].abs().max())<=.750001;assert float(a['correction'].abs().max())<=1.500001
