import numpy as np
import pandas as pd
import torch
from types import SimpleNamespace


def _model():
    from suite14_models import AuthoritySafeCollaborativeMoE
    return AuthoritySafeCollaborativeMoE(
        flat_dim=8,e0_context_dim=3,gate_context_dim=5,fusion_context_dim=5,
        e1_context_dim=4,e2_context_dim=3,e3_context_dim=4,e4_context_dim=3,
        student_dim=4,course_dim=5,relation_dim=7,component_numeric_dim=6,
        n_faculties=2,n_component_types=6,d_model=16,dropout=0.,e0_dropout=0.,expert_dropout=0.,
    )


def _forward(m,b=4):
    return m(
        flat=torch.randn(b,8),e0_context=torch.randn(b,3),gate_context=torch.randn(b,5),fusion_context=torch.randn(b,5),
        e1_context=torch.randn(b,4),e2_context=torch.randn(b,3),e3_context=torch.randn(b,4),e4_context=torch.randn(b,3),
        faculty=torch.zeros(b,dtype=torch.long),committee_probs=torch.rand(b,3)*.8+.1,
        student_seq=torch.randn(b,2,4),student_mask=torch.ones(b,2,dtype=torch.bool),
        course_target=torch.randn(b,5),course_neighbors=torch.randn(b,2,5),course_neighbor_mask=torch.ones(b,2,dtype=torch.bool),course_relation_type=torch.ones(b,2,dtype=torch.long),
        relation_events=torch.randn(b,3,7),relation_mask=torch.ones(b,3,dtype=torch.bool),relation_type=torch.ones(b,3,dtype=torch.long),
        component_events=torch.randn(b,3,6),component_mask=torch.ones(b,3,dtype=torch.bool),component_type=torch.ones(b,3,dtype=torch.long),
    )


def test_suite14_initial_collaboration_is_exact_e0_identity():
    m=_model();m.eval();o=_forward(m)
    assert torch.allclose(o['full_collab_logit'],o['private_logits'][:,0],atol=1e-7)
    assert torch.allclose(o['collab_delta_logit'],torch.zeros_like(o['collab_delta_logit']),atol=1e-7)


def test_external_authority_zero_is_exact_e0_even_after_nonzero_delta():
    from suite14_models import apply_authority
    e0=torch.tensor([-.5,.3]);delta=torch.tensor([2.,-1.]);row=torch.tensor([.8,.2])
    assert torch.allclose(apply_authority(e0,delta,row,0.),e0)
    got=apply_authority(e0,delta,row,.5)
    assert torch.allclose(got,e0+.5*row*delta)


def test_gate_context_has_no_absolute_semester_signal():
    from suite14_pipeline import build_context_views,context_feature_names
    names=['target_semester_registered_credits','hist_warning_rate','course_history_missing_flag','student_gpa_history_missing_flag']
    raw=np.zeros((2,len(names)),np.float32);support=pd.DataFrame({'history_semesters':[2,4],'history_rows':[9,25],'course_prior_rows':[3,80],'new_student':[0,0],'new_course':[1,0]})
    a=build_context_views(raw,names,support,np.array([20221,20222]));b=build_context_views(raw,names,support,np.array([20301,20302]))
    assert np.array_equal(a['gate'],b['gate'])
    assert 'target_semester_ordinal' not in context_feature_names()['gate']
    assert a['gate'].shape[1]==5


def test_local_competence_features_capture_predictions_disagreement_confidence_and_availability():
    from suite14_models import local_competence_features
    logits=torch.tensor([[0.,1.,-1.,2.,-2.]])
    avail=torch.tensor([[1,1,1,0,1]],dtype=torch.bool)
    x=local_competence_features(logits,avail)
    assert x.shape==(1,19)
    p=torch.sigmoid(logits)
    assert torch.allclose(x[:,:5],p)
    assert torch.allclose(x[:,5:9],torch.abs(p[:,1:]-p[:,:1]))
    assert torch.allclose(x[:,-5:],avail.float())


def test_phase2_and_phase3_have_zero_epoch_identity_option():
    from suite14_training import phase_allows_zero
    assert phase_allows_zero(0)
    assert not phase_allows_zero(1)
    assert phase_allows_zero(2)
    assert phase_allows_zero(3)


def test_phase3_freezes_e0_but_updates_specialists_and_collaboration():
    from suite14_training import set_phase_trainable
    m=_model();set_phase_trainable(m,3)
    assert not any(p.requires_grad for p in m.e0.parameters())
    assert any(p.requires_grad for p in m.e3.parameters())
    assert any(p.requires_grad for p in m.correction.parameters())
    assert any(p.requires_grad for p in m.authority.parameters())


def test_phase1_selection_balances_mechanism_fidelity_and_failure_prediction():
    from suite14_training import specialist_validation_stats
    faculty=np.array([0,0,0,0,1,1,1,1]);y=np.array([0,1,0,1,0,1,0,1])
    target=np.tile(np.array([[.2,.3,0.,.4],[.8,.3,1.,.7],[.2,.3,0.,.4],[.8,.3,1.,.7]]),(2,1))[:8]
    # A reconstructs mechanisms well but ranks private failure predictions backwards.
    mech_a=np.clip(target,.01,.99);private_a=np.tile(np.array([[.8,.8,.8,.8,.8],[.2,.2,.2,.2,.2],[.8,.8,.8,.8,.8],[.2,.2,.2,.2,.2]]),(2,1))[:8]
    # B has slightly worse mechanism fidelity but strong failure ranking.
    mech_b=np.clip(.9*target+.05,.01,.99);private_b=np.tile(np.array([[.1,.1,.1,.1,.1],[.9,.9,.9,.9,.9],[.1,.1,.1,.1,.1],[.9,.9,.9,.9,.9]]),(2,1))[:8]
    a=specialist_validation_stats(target,mech_a,private_a,y,faculty,['a','b'],predictive_weight=1.0,direct_weights=(.5,.1,1.,.35))
    b=specialist_validation_stats(target,mech_b,private_b,y,faculty,['a','b'],predictive_weight=1.0,direct_weights=(.5,.1,1.,.35))
    assert b['score']>a['score']


def test_authority_grid_can_choose_exact_zero_when_collaboration_hurts():
    from suite14_authority import select_faculty_authority
    y=np.array([0,1,0,1,0,1,0,1]);e0=np.array([.1,.9,.2,.8,.1,.9,.2,.8]);full=np.array([.9,.1,.8,.2,.9,.1,.8,.2])
    # Decompose full as e0_logit + row*delta; row=1.
    logit=lambda p:np.log(np.clip(p,1e-5,1-1e-5)/(1-np.clip(p,1e-5,1-1e-5)))
    r=select_faculty_authority(y,logit(e0),logit(full)-logit(e0),np.ones(len(y)),grid=[0,.25,.5,.75,1],beta=2.)
    assert r['authority']==0.0


def test_authority_grid_selects_nonzero_when_consistently_better():
    from suite14_authority import select_faculty_authority
    y=np.array([0,1,0,1,0,1,0,1]);e0=np.array([.7,.55,.6,.45,.7,.55,.6,.45]);full=np.array([.1,.9,.2,.8,.1,.9,.2,.8])
    logit=lambda p:np.log(np.clip(p,1e-5,1-1e-5)/(1-np.clip(p,1e-5,1-1e-5)))
    r=select_faculty_authority(y,logit(e0),logit(full)-logit(e0),np.ones(len(y)),grid=[0,.25,.5,.75,1],beta=2.)
    assert r['authority']>0
    assert r['delta_ap']>0


def test_deployment_policy_uses_broad_success_and_strong_local_fallback():
    from suite14_authority import deployment_authorities
    rows=[
        {'faculty':'a','authority':1.0,'delta_ap':.03,'delta_f2':.01,'ap_wins':2,'blocks':2},
        {'faculty':'b','authority':.75,'delta_ap':-.01,'delta_f2':.02,'ap_wins':1,'blocks':2},
    ]
    auth,info=deployment_authorities(rows,['a','b'],broad_success=False,local_min_ap=.01,local_min_f2=0.,local_min_win_fraction=.5)
    assert auth['a']==1.0
    assert auth['b']==0.0
    assert info['mode']=='local_safe_fallback'

def test_launcher_invokes_existing_suite14_trainer():
    from pathlib import Path
    root=Path(__file__).resolve().parents[1]
    text=(root/'run_suite14.sh').read_text()
    expected='train_suite14_authority_safe_collaborative_moe.py'
    assert expected in text
    assert (root/expected).exists()
