from __future__ import annotations

from typing import Dict, Iterable, List, Sequence, Tuple

import numpy as np


def _rankdata(values: np.ndarray) -> np.ndarray:
    a = np.asarray(values, dtype=float)
    order = np.argsort(a, kind="mergesort")
    sorted_a = a[order]
    ranks = np.arange(1, len(a) + 1, dtype=float)
    i = 0
    while i < len(sorted_a):
        j = i
        while j + 1 < len(sorted_a) and sorted_a[j + 1] == sorted_a[i]:
            j += 1
        if j > i:
            ranks[i : j + 1] = (i + 1 + j + 1) / 2.0
        i = j + 1
    out = np.empty(len(a), dtype=float)
    out[order] = ranks
    return out


def roc_auc(y_bin: np.ndarray, score: np.ndarray) -> float:
    y = np.asarray(y_bin).astype(bool)
    n_pos = int(y.sum())
    n_neg = int((~y).sum())
    if n_pos == 0 or n_neg == 0:
        return float("nan")
    ranks = _rankdata(np.asarray(score, dtype=float))
    return float(
        (ranks[y].sum() - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)
    )


def average_precision(y_bin: np.ndarray, score: np.ndarray) -> float:
    y = np.asarray(y_bin).astype(int)
    n_pos = int(y.sum())
    if n_pos == 0:
        return float("nan")
    order = np.argsort(-np.asarray(score, dtype=float), kind="mergesort")
    sorted_y = y[order]
    tp = np.cumsum(sorted_y)
    fp = np.cumsum(1 - sorted_y)
    precision = tp / np.maximum(tp + fp, 1)
    recall = tp / n_pos
    previous = np.concatenate([[0.0], recall[:-1]])
    return float(np.sum((recall - previous) * precision))


def confusion_metrics(y_bin: np.ndarray, warn: np.ndarray) -> Dict[str, float]:
    y = np.asarray(y_bin).astype(bool)
    w = np.asarray(warn).astype(bool)
    tp = int((y & w).sum())
    fp = int((~y & w).sum())
    fn = int((y & ~w).sum())
    tn = int((~y & ~w).sum())
    n = tp + fp + fn + tn
    precision = tp / (tp + fp) if tp + fp else float("nan")
    recall = tp / (tp + fn) if tp + fn else float("nan")
    f1 = (
        2 * precision * recall / (precision + recall)
        if np.isfinite(precision) and np.isfinite(recall) and precision + recall > 0
        else 0.0
    )
    f2 = (
        5 * precision * recall / (4 * precision + recall)
        if np.isfinite(precision) and np.isfinite(recall) and 4 * precision + recall > 0
        else 0.0
    )
    return {
        "tn": tn,
        "fp": fp,
        "fn": fn,
        "tp": tp,
        "accuracy": (tp + tn) / n if n else float("nan"),
        "precision": precision,
        "recall": recall,
        "specificity": tn / (tn + fp) if tn + fp else float("nan"),
        "f1": f1,
        "f2": f2,
        "flag_rate": (tp + fp) / n if n else float("nan"),
        "flagged": tp + fp,
    }


def best_f1_threshold(
    y_bin: np.ndarray,
    score: np.ndarray,
    min_flag: int = 5,
) -> Tuple[float, Dict[str, float]]:
    y = np.asarray(y_bin).astype(bool)
    s = np.asarray(score, dtype=float)
    order = np.argsort(-s, kind="mergesort")
    sorted_y = y[order]
    tp = np.cumsum(sorted_y)
    fp = np.cumsum(~sorted_y)
    fn = int(y.sum()) - tp
    precision = tp / np.maximum(tp + fp, 1)
    recall = tp / np.maximum(tp + fn, 1)
    f1 = 2 * precision * recall / np.maximum(precision + recall, 1e-12)
    valid = np.arange(1, len(s) + 1) >= min_flag
    if not valid.any():
        idx = len(s) - 1
    else:
        masked = np.where(valid, f1, -1.0)
        idx = int(np.argmax(masked))
    if idx == len(s) - 1:
        threshold = float(s[order[idx]] - 1e-12)
    else:
        threshold = float((s[order[idx]] + s[order[idx + 1]]) / 2.0)
    metrics = confusion_metrics(y, s >= threshold)
    return threshold, metrics


def warn_by_rate(score: np.ndarray, rate: float) -> np.ndarray:
    s = np.asarray(score, dtype=float)
    n = len(s)
    k = int(np.clip(round(n * float(rate)), 0, n))
    warn = np.zeros(n, dtype=bool)
    if k > 0:
        idx = np.argpartition(-s, k - 1)[:k]
        warn[idx] = True
    return warn


def equal_budget_metrics(records: Sequence[Dict[str, np.ndarray]], rate: float) -> Dict[str, float]:
    ys = []
    warns = []
    for record in records:
        ys.append(np.asarray(record["y_bin"]).astype(bool))
        warns.append(warn_by_rate(np.asarray(record["score"]), rate))
    return confusion_metrics(np.concatenate(ys), np.concatenate(warns))
