import numpy as np
import pandas as pd
import pytest


def test_common_feature_alignment_uses_names():
    from suite6_common import align_raw_features
    X = np.array([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]])
    out = align_raw_features(X, ["b", "c", "a"], ["a", "b"])
    np.testing.assert_array_equal(out, np.array([[30.0, 10.0], [60.0, 40.0]]))


def test_latest_block_split_is_chronological_for_one_faculty():
    from suite6_common import latest_block_split
    faculty = np.zeros(8, dtype=int)
    blocks = np.array([1, 1, 2, 2, 3, 3, 4, 4], float)
    tr, va = latest_block_split(faculty, blocks, val_blocks=2)
    assert set(np.where(va)[0]) == {4, 5, 6, 7}
    assert set(np.where(tr)[0]) == {0, 1, 2, 3}


def test_zero_initialized_target_only_residual_moe_is_exact_committee():
    torch = pytest.importorskip("torch")
    from suite6_residual_moe import ResidualMoE
    model = ResidualMoE(
        input_dim=6,
        n_faculties=1,
        n_experts=4,
        faculty_dim=8,
        encoder_hidden=12,
        representation_dim=8,
        expert_hidden=6,
        delta_max=2.0,
        dropout=0.0,
    )
    x = torch.randn(10, 6)
    f = torch.zeros(10, dtype=torch.long)
    q = torch.linspace(0.05, 0.95, 10)
    out = model(x, f, q)
    torch.testing.assert_close(out["final_prob"], q, rtol=1e-5, atol=1e-6)
    assert out["weights"].shape == (10, 5)
    assert torch.max(torch.abs(out["residuals"])) <= 2.0 + 1e-6


def test_capability_target_prefers_helpful_expert():
    torch = pytest.importorskip("torch")
    from suite6_residual_moe import capability_targets
    y = torch.tensor([1.0, 0.0])
    q = torch.tensor([0.2, 0.8])
    cf = torch.tensor([[0.8, 0.1], [0.2, 0.9]])
    target, utility = capability_targets(y, q, cf, temperature=0.25)
    assert torch.all(utility[:, 0] > utility[:, 1])
    assert torch.all(target[:, 1] > target[:, 2])


def test_reference_log_parser_handles_v2_and_council(tmp_path):
    from collect_reference_metrics import parse_reference_log
    v2 = tmp_path / "v2_khoa_demo.log"
    v2.write_text(
        "### HOLDOUT (test) [signal=classifier, beta=2]\n"
        "POOLED   1000  10.00% |  0.4000  0.8000 |  0.3000  0.6000  0.4000  0.5000   20.00% |  0.3500  0.5500  0.4300  0.5000   15.00%\n"
    )
    rows = parse_reference_log(v2, faculty="khoa_demo", default_model="v2")
    assert len(rows) == 1
    assert rows[0]["model"] == "v2"
    assert np.isclose(rows[0]["fixed_f2"], 0.5)

    council = tmp_path / "council_khoa_demo.log"
    council.write_text(
        "### HOLDOUT (test) [model=competence_council, beta=2]\n"
        "POOLED   1000  10.00% |  0.4500  0.8200 |  0.3200  0.6200  0.4200  0.5200   20.00% |  0.3700  0.5700  0.4500  0.5300   15.00%\n"
    )
    rows = parse_reference_log(council, faculty="khoa_demo")
    assert rows[0]["model"] == "competence_council"
    assert np.isclose(rows[0]["drift_f2"], 0.53)


def test_drift_rate_uses_previous_fold_prevalence():
    from suite6_eval import drift_rate_for_fold
    prevalences = {5: 0.05, 6: 0.10, 7: 0.15}
    assert np.isclose(drift_rate_for_fold(6, 2.0, prevalences, 0.03), 0.10)
    assert np.isclose(drift_rate_for_fold(7, 2.0, prevalences, 0.03), 0.20)
