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.stability import (
    binary_auc,
    score_temporal_stability,
    select_temporally_stable_features,
)


def test_binary_auc_handles_ties_and_direction():
    y = np.array([0, 0, 1, 1])
    assert binary_auc(np.array([0, 1, 2, 3]), y) == 1.0
    assert binary_auc(np.array([3, 2, 1, 0]), y) == 0.0
    assert binary_auc(np.ones(4), y) == 0.5


def test_temporal_selection_keeps_stable_and_rejects_direction_reversal_and_sparse():
    semesters = np.repeat([1, 2, 3, 4], 8)
    y = np.tile([0, 0, 0, 0, 1, 1, 1, 1], 4)
    stable = np.tile([0, 1, 2, 3, 6, 7, 8, 9], 4)
    reverse = stable.copy()
    reverse[semesters >= 3] *= -1
    sparse = stable.astype(float)
    sparse[:28] = np.nan
    protected = np.ones_like(stable, dtype=float)
    X = pd.DataFrame({"stable": stable, "reverse": reverse, "sparse": sparse, "prev_semester_gpa10": protected})
    config = replace(
        SuiteConfig(),
        stability_min_observed_rate=0.20,
        stability_min_nonconstant_semester_rate=0.75,
        stability_min_median_strength=0.10,
        stability_min_direction_consistency=0.75,
        stability_min_valid_semesters=3,
    )
    selected, report = select_temporally_stable_features(X, y, semesters, config)
    assert "stable" in selected
    assert "reverse" not in selected
    assert "sparse" not in selected
    assert "prev_semester_gpa10" in selected
    row = report.set_index("feature").loc["stable"]
    assert row["direction_consistency"] == 1.0
    assert row["selected"]


def test_temporal_report_is_deterministic_and_complete():
    X = pd.DataFrame({"x": [0, 1, 2, 3, 0, 1, 2, 3]})
    y = np.array([0, 0, 1, 1, 0, 0, 1, 1])
    sem = np.array([1, 1, 1, 1, 2, 2, 2, 2])
    report = score_temporal_stability(X, y, sem, SuiteConfig())
    assert list(report["feature"]) == ["x"]
    assert report.loc[0, "valid_semesters"] == 2
    assert np.isfinite(report.loc[0, "priority_score"])
