"""Classification metrics written from scratch, the way interviewers ask you to explain them."""
from __future__ import annotations

import math


def confusion_counts(y_true: list[int], y_pred: list[int]) -> dict[str, int]:
    tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
    fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
    fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)
    tn = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 0)
    return {"tp": tp, "fp": fp, "fn": fn, "tn": tn}


def precision_recall_f1(y_true: list[int], y_pred: list[int]) -> tuple[float, float, float]:
    c = confusion_counts(y_true, y_pred)
    precision = c["tp"] / (c["tp"] + c["fp"]) if c["tp"] + c["fp"] else 0.0
    recall = c["tp"] / (c["tp"] + c["fn"]) if c["tp"] + c["fn"] else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return precision, recall, f1


def roc_auc(y_true: list[int], scores: list[float]) -> float:
    """AUC = probability a random positive scores above a random negative (ties count half).

    Uses the rank-sum (Mann-Whitney U) identity, O(n log n).
    """
    pairs = sorted(zip(scores, y_true))
    n_pos = sum(y_true)
    n_neg = len(y_true) - n_pos
    if n_pos == 0 or n_neg == 0:
        raise ValueError("need at least one positive and one negative")
    rank_sum = 0.0
    i = 0
    while i < len(pairs):
        j = i
        while j < len(pairs) and pairs[j][0] == pairs[i][0]:
            j += 1
        avg_rank = (i + 1 + j) / 2  # ranks are 1-based; tied block gets the average
        rank_sum += avg_rank * sum(label for _, label in pairs[i:j])
        i = j
    u = rank_sum - n_pos * (n_pos + 1) / 2
    return u / (n_pos * n_neg)


def log_loss(y_true: list[int], probs: list[float], eps: float = 1e-15) -> float:
    total = 0.0
    for t, p in zip(y_true, probs):
        p = min(max(p, eps), 1 - eps)
        total += -(t * math.log(p) + (1 - t) * math.log(1 - p))
    return total / len(y_true)


def kmeans_1d(points: list[float], k: int, iters: int = 50) -> list[float]:
    """Tiny Lloyd's algorithm on 1-D data, deterministic init at evenly spaced quantiles."""
    pts = sorted(points)
    centers = [pts[int(i * (len(pts) - 1) / max(k - 1, 1))] for i in range(k)]
    for _ in range(iters):
        groups: list[list[float]] = [[] for _ in range(k)]
        for x in pts:
            groups[min(range(k), key=lambda c: abs(x - centers[c]))].append(x)
        new = [sum(g) / len(g) if g else centers[i] for i, g in enumerate(groups)]
        if new == centers:
            break
        centers = new
    return centers
