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.experiments import EXPERIMENTS
from experiment_b_suite.features import build_experiment_features


def _raw():
    sem = np.repeat([1, 2, 3], 8)
    yb = np.tile([0, 0, 0, 0, 1, 1, 1, 1], 3)
    grades = np.where(yb == 1, 4.0, 8.0)
    stable = np.tile([0, 1, 2, 3, 6, 7, 8, 9], 3)
    frame = pd.DataFrame(
        {
            "IDSV": np.arange(24),
            "IDMH": 1,
            "IDKQDK": np.arange(24),
            "target_NHHK": sem,
            "target_semester_ordinal": sem,
            "target_grade10": grades,
            "target_grade4": 1,
            "stable": stable,
            "stable_copy": stable * 2,
            "noise": np.arange(24) % 3,
            "hist_same_course_attempts": np.tile([0, 1], 12),
            "hist_target_course_count": 2,
            "hist_component_grade_count": 3,
            "recent3_component_grade_mean": 7.0,
            "prev_conduct_score": 80.0,
            "prev_semester_gpa10": stable,
            "course_status_a": np.tile([0, 1, 2], 8),
            "course_status_b": np.tile([1, 2, 0], 8),
        }
    )
    return frame, frame.iloc[:4].copy()


def test_b0_exactly_preserves_baseline_features():
    train, test = _raw()
    result = build_experiment_features(train, test, EXPERIMENTS["B0"], SuiteConfig())
    assert "stable" in result.train
    assert "stable_copy" in result.train
    assert "IDSV" not in result.train
    assert result.manifest["pipeline"] == "baseline"


def test_b4_prunes_correlated_stable_features_and_b5_adds_masks():
    train, test = _raw()
    config = replace(
        SuiteConfig(),
        stability_min_observed_rate=0.0,
        stability_min_nonconstant_semester_rate=0.5,
        stability_min_median_strength=0.05,
        stability_min_direction_consistency=0.6,
        stability_min_valid_semesters=2,
    )
    b4 = build_experiment_features(train, test, EXPERIMENTS["B4"], config)
    assert not ({"stable", "stable_copy"} <= set(b4.train.columns))
    assert b4.manifest["pipeline"] == "stable_core"

    b5 = build_experiment_features(train, test, EXPERIMENTS["B5"], config)
    assert "eb_same_course_history_available" in b5.train
    assert b5.preprocessing_mode == "missing_aware"


def test_b6_branches_from_b4_and_b7_replaces_status_and_b8_adds_risk_bins():
    train, test = _raw()
    config = replace(
        SuiteConfig(),
        stability_min_observed_rate=0.0,
        stability_min_nonconstant_semester_rate=0.5,
        stability_min_median_strength=0.05,
        stability_min_direction_consistency=0.6,
        stability_min_valid_semesters=2,
        risk_bin_min_history_rows=1,
        risk_bin_count=2,
    )
    b6 = build_experiment_features(train, test, EXPERIMENTS["B6_Q"], config)
    assert "eb_same_course_history_available" not in b6.train
    assert b6.preprocessing_mode == "quantile_rank"

    b7 = build_experiment_features(train, test, EXPERIMENTS["B7"], config)
    assert not any(c.startswith("course_status_") for c in b7.train)
    assert "eb_course_status_count_0" in b7.train

    b8 = build_experiment_features(train, test, EXPERIMENTS["B8"], config)
    assert "eb_riskbin__prev_semester_gpa10" in b8.train
