import numpy as np
import torch

from suite22_models import Suite22Model, FeatureAwareModulator


def make_model(variant='sftr_tabm'):
    f=12;k=3
    knots=np.zeros((f,k),np.float32);mask=np.ones((f,k),bool)
    return Suite22Model(
        variant=variant,knots=knots,knot_mask=mask,n_faculties=3,
        student_dim=5,course_dim=4,relation_dim=3,component_dim=3,
        relation_types=20,component_types=10,course_relation_types=20,
        token_dim=3,faculty_dim=6,time_dim=6,modulation_rank=4,graph_neighbors=3,
        relation_out_dim=8,ensemble_members=4,tabm_blocks=2,tabm_width=24,dropout=.0,
        backend='internal_smoke')


def batch(b=7):
    return dict(
        current=torch.randn(b,12),faculty_idx=torch.randint(0,3,(b,)),
        semester_ordinal=torch.arange(b).float()+6000,semester_z=torch.randn(b),
        course_target=torch.randn(b,4),student_seq=torch.randn(b,3,5),student_mask=torch.ones(b,3,dtype=torch.bool),
        course_neighbors=torch.randn(b,2,4),course_neighbor_mask=torch.ones(b,2,dtype=torch.bool),course_relation_type=torch.randint(0,6,(b,2)),
        relation_events=torch.randn(b,4,3),relation_mask=torch.ones(b,4,dtype=torch.bool),relation_type=torch.randint(0,10,(b,4)),
        component_events=torch.randn(b,5,3),component_mask=torch.ones(b,5,dtype=torch.bool),component_type=torch.randint(0,8,(b,5)),
    )


def test_all_variants_forward():
    for v in ['shared_tabm','faculty_mod_tabm','faculty_time_tabm','relational_ft_tabm','sftr_tabm']:
        m=make_model(v);o=m(**batch())
        assert o['member_probabilities'].shape==(7,4)
        assert o['probability'].shape==(7,)
        assert torch.isfinite(o['probability']).all()


def test_modulator_starts_as_identity():
    mod=FeatureAwareModulator(6,6,12,rank=4)
    x=torch.randn(5,12,3);f=torch.randn(5,6);t=torch.randn(5,6)
    y,(g,b,l),_=mod(x,f,t,True,True,True)
    assert torch.allclose(y,x,atol=1e-6)
    assert torch.allclose(g,torch.ones_like(g),atol=1e-6)
    assert torch.allclose(b,torch.zeros_like(b),atol=1e-6)
    assert torch.allclose(l,torch.zeros_like(l),atol=1e-6)


def test_graph_ablation_changes_path_but_keeps_shape():
    m=make_model('sftr_tabm');x=batch()
    a=m(**x)['probability'];b=m(**x,ablation='graph_off')['probability']
    assert a.shape==b.shape


def test_zero_relations_is_finite():
    m=make_model('sftr_tabm');o=m(**batch(),ablation='zero_relations')
    assert torch.isfinite(o['probability']).all()
