from __future__ import annotations

from dataclasses import replace

import numpy as np
import pandas as pd

from experiment_b_suite.config import SuiteConfig
from experiment_b_suite.risk_bins import build_cross_fitted_risk_bins


def _train(labels_last=(0.0, 1.0)):
    return pd.DataFrame(
        {
            "target_semester_ordinal": [1, 1, 1, 1, 2, 2, 2, 2, 3, 3],
            "target_grade10": [8, 7, 4, 3, 9, 8, 2, 1, 8 if labels_last[0] == 0 else 4, 4 if labels_last[1] == 1 else 8],
            "prev_semester_gpa10": [2, 3, 8, 9, 2, 3, 8, 9, 2, np.nan],
        }
    )


def test_future_labels_do_not_change_earlier_semester_features_and_first_semester_is_fixed_prior():
    config = replace(SuiteConfig(), risk_bin_min_history_rows=1, risk_bin_count=2, risk_bin_alpha=1.0)
    test = pd.DataFrame({"target_semester_ordinal": [4], "target_grade10": [8], "prev_semester_gpa10": [8.5]})
    a = build_cross_fitted_risk_bins(_train((0, 1)), test, ["prev_semester_gpa10"], config)
    b = build_cross_fitted_risk_bins(_train((1, 0)), test, ["prev_semester_gpa10"], config)
    col = "eb_riskbin__prev_semester_gpa10"
    assert np.allclose(a.train.loc[:3, col], 0.05)
    assert np.allclose(a.train.loc[4:7, col], b.train.loc[4:7, col])


def test_same_semester_labels_are_excluded_and_test_uses_all_training_history():
    config = replace(SuiteConfig(), risk_bin_min_history_rows=1, risk_bin_count=2, risk_bin_alpha=1.0)
    train = _train((0, 1))
    test = pd.DataFrame({"target_semester_ordinal": [4, 4], "target_grade10": [8, 8], "prev_semester_gpa10": [8.5, np.nan]})
    result = build_cross_fitted_risk_bins(train, test, ["prev_semester_gpa10"], config)
    col = "eb_riskbin__prev_semester_gpa10"
    # Semester 2 features are determined only by semester 1, so equal-valued rows share a mapping.
    assert result.train.loc[6, col] == result.train.loc[7, col]
    assert np.isfinite(result.test[col]).all()
    assert result.manifest["features"]["prev_semester_gpa10"]["test_history_rows"] == len(train)
