from __future__ import annotations

import numpy as np

from early_warning_suite.metrics import average_precision, confusion_metrics, equal_budget_metrics, roc_auc


def test_perfect_ranking_metrics_are_one():
    y = np.array([0, 1, 0, 1])
    score = np.array([0.1, 0.9, 0.2, 0.8])
    assert average_precision(y, score) == 1.0
    assert roc_auc(y, score) == 1.0


def test_confusion_matrix_uses_failure_as_positive():
    m = confusion_metrics(np.array([1, 1, 0, 0]), np.array([1, 0, 1, 0]))
    assert (m["tp"], m["fn"], m["fp"], m["tn"]) == (1, 1, 1, 1)


def test_equal_budget_flags_requested_top_rate_per_fold():
    records = [
        {"fold": 1, "y_bin": np.array([1, 0, 0, 0]), "score": np.array([0.9, 0.8, 0.2, 0.1])},
        {"fold": 2, "y_bin": np.array([0, 1, 0, 0]), "score": np.array([0.8, 0.9, 0.2, 0.1])},
    ]
    m = equal_budget_metrics(records, 0.25)
    assert m["flagged"] == 2
    assert m["tp"] == 2
