import sys
from pathlib import Path
import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
PARENT = ROOT.parent
for p in [str(ROOT), str(PARENT)]:
    if p not in sys.path:
        sys.path.insert(0, p)


def test_v2_meta_features_three_experts_has_13_columns():
    from suite2_common import v2_meta_features
    p = np.array([[0.1, 0.2, 0.3], [0.7, 0.6, 0.8]], float)
    z, names = v2_meta_features(p)
    assert z.shape == (2, 13)
    assert len(names) == 13
    assert np.isfinite(z).all()


def test_chronological_support_uses_strictly_prior_semesters():
    from suite2_common import chronological_support_features
    hist = pd.DataFrame({
        'IDSV': ['A','A','A','B','B'],
        'IDMH': ['C1','C2','C3','C1','C4'],
        'target_semester_ordinal': [1,1,2,1,3],
    })
    target = pd.DataFrame({
        'IDSV': ['A','B','C'],
        'IDMH': ['C4','C5','C1'],
        'target_semester_ordinal': [3,4,4],
    })
    h = chronological_support_features(hist)
    t = chronological_support_features(hist, target)
    # A has zero prior semesters for semester 1 rows and one prior semester at semester 2.
    assert h['history_semesters'].tolist() == [0,0,1,0,1]
    # Target A has semesters 1 and 2; B has semesters 1 and 3; C is unseen.
    assert t['history_semesters'].tolist() == [2,2,0]
    assert t['new_student'].tolist() == [0.0,0.0,1.0]
    assert t['new_course'].tolist() == [1.0,1.0,0.0]


def test_history_regime_labels_are_deterministic():
    from suite2_common import history_regime_labels
    d = np.array([0,1,2,3,7])
    assert history_regime_labels(d).tolist() == ['history0','history1_2','history1_2','history3plus','history3plus']


def test_blend_authority_zero_is_exact_committee():
    from suite2_common import blend_probability
    q = np.array([0.1,0.4,0.8])
    s = np.array([0.9,0.2,0.3])
    assert np.allclose(blend_probability(q, s, 0.0), q)


def test_window_indices_respect_recent_block_count():
    from suite2_common import window_indices_before_block
    blocks = np.array([1,1,2,2,3,3,4,4], float)
    idx = window_indices_before_block(blocks, target_block=4, recent_blocks=2)
    assert idx.tolist() == [2,3,4,5]
    all_idx = window_indices_before_block(blocks, target_block=4, recent_blocks=None)
    assert all_idx.tolist() == [0,1,2,3,4,5]


def test_hgb_probability_shape_and_range():
    from suite2_common import fit_hgb_classifier, predict_positive
    rng = np.random.default_rng(3)
    X = rng.normal(size=(120, 6))
    y = (X[:,0] + 0.5*X[:,1] > 0.3).astype(int)
    m = fit_hgb_classifier(X, y, seed=2, max_iter=20, max_leaf_nodes=7, min_samples_leaf=5)
    p = predict_positive(m, X[:11])
    assert p.shape == (11,)
    assert np.all((p > 0) & (p < 1))


def test_relational_stack_feature_shape_with_four_experts():
    from suite2_common import v2_meta_features, relational_competence_features
    p4 = np.array([[.1,.2,.3,.4],[.6,.7,.8,.5]])
    meta, _ = v2_meta_features(p4)
    support = pd.DataFrame({
        'history_semesters':[0,3], 'history_rows':[0,10], 'new_student':[1.,0.],
        'course_prior_rows':[5,20], 'new_course':[0.,0.]
    })
    z, names = relational_competence_features(p4, support)
    assert z.shape[0] == 2
    assert z.shape[1] == meta.shape[1] + 5 + 2
    assert len(names) == z.shape[1]


def test_a_routed_candidate_only_changes_routed_rows():
    from exp_a_tree_specialist import apply_routed_blend
    q = np.array([.1,.2,.3,.4])
    s = np.array([.9,.8,.7,.6])
    r = np.array([False,True,False,True])
    out = apply_routed_blend(q,s,r,.5)
    assert out[0] == q[0] and out[2] == q[2]
    assert np.allclose(out[r], .5*q[r] + .5*s[r])


def test_b_make_stack_features_contains_relational_and_support():
    from exp_b_relational_stacker import make_stack_features
    tree = np.array([[.1,.2,.3],[.5,.6,.7]])
    rel = np.array([.4,.8])
    support = pd.DataFrame({'history_semesters':[0,3],'history_rows':[0,8],'new_student':[1.,0.],'course_prior_rows':[4,20],'new_course':[0.,0.]})
    z,names = make_stack_features(tree,rel,support)
    assert z.shape[0] == 2
    assert 'relational_minus_tree_committee' in names
    assert 'new_student' in names


def test_c_no_history_feature_indices_drop_history_prefixes():
    from exp_c_history_regime import no_history_feature_indices
    names = ['prev_gpa','hist_grade','recent3_x','admission_score','course_fail_rate','foo']
    idx = no_history_feature_indices(names)
    kept = [names[i] for i in idx]
    assert kept == ['admission_score','course_fail_rate','foo']


def test_d_candidate_window_names_are_stable():
    from exp_d_multiwindow import window_specs
    assert window_specs() == [('all',None),('last6',6),('last4',4),('last2',2)]


def test_window_indices_accept_string_encoded_temporal_blocks():
    from suite2_common import window_indices_before_block
    blocks = np.array(['1.0','1.0','2.0','3.0','4.0'], dtype=object)
    idx = window_indices_before_block(blocks, target_block='4.0', recent_blocks=2)
    assert idx.tolist() == [2,3]
