from __future__ import annotations

import numpy as np
import pandas as pd

from early_warning_suite.config import SuiteConfig
from early_warning_suite.historical import build_leak_safe_historical_features


def test_same_semester_labels_do_not_affect_same_semester_features(synthetic_frames):
    train, test = synthetic_frames
    config = SuiteConfig()
    a_train, _ = build_leak_safe_historical_features(train, test, config)

    changed = train.copy()
    changed.loc[changed["target_semester_ordinal"] == 3, "target_grade10"] = [0.0, 10.0]
    b_train, _ = build_leak_safe_historical_features(changed, test, config)

    mask = train["target_semester_ordinal"].eq(3)
    pd.testing.assert_frame_equal(
        a_train.loc[mask].reset_index(drop=True),
        b_train.loc[mask].reset_index(drop=True),
        check_dtype=False,
    )


def test_future_labels_do_not_affect_earlier_features(synthetic_frames):
    train, test = synthetic_frames
    config = SuiteConfig()
    a_train, _ = build_leak_safe_historical_features(train, test, config)
    changed = train.copy()
    changed.loc[changed["target_semester_ordinal"] == 3, "target_grade10"] = 0.0
    b_train, _ = build_leak_safe_historical_features(changed, test, config)
    mask = train["target_semester_ordinal"].lt(3)
    pd.testing.assert_frame_equal(
        a_train.loc[mask].reset_index(drop=True),
        b_train.loc[mask].reset_index(drop=True),
        check_dtype=False,
    )


def test_test_labels_are_not_read_and_new_entities_are_marked(synthetic_frames):
    train, test = synthetic_frames
    config = SuiteConfig()
    _, a_test = build_leak_safe_historical_features(train, test, config)
    changed = test.copy()
    changed["target_grade10"] = [0.0, 0.0]
    _, b_test = build_leak_safe_historical_features(train, changed, config)
    pd.testing.assert_frame_equal(a_test, b_test, check_dtype=False)
    assert a_test.loc[0, "eng_student_seen_before"] == 1.0
    assert a_test.loc[1, "eng_student_seen_before"] == 0.0
    assert a_test.loc[0, "eng_repeat_course_flag"] == 1.0
    assert a_test.loc[1, "eng_course_seen_before"] == 0.0


def test_empirical_bayes_course_rate_is_shrunk(synthetic_frames):
    train, test = synthetic_frames
    config = SuiteConfig(course_prior_strength=50.0, default_failure_prior=0.05)
    _, test_hist = build_leak_safe_historical_features(train, test, config)
    raw = test_hist.loc[0, "eng_course_prior_failure_rate"]
    smoothed = test_hist.loc[0, "eng_course_smoothed_failure_rate"]
    global_rate = (train["target_grade10"] < 5).mean()
    assert min(raw, global_rate) <= smoothed <= max(raw, global_rate)
