"""Exact whole-cell metrics and explicitly distinct warning policies."""
from __future__ import annotations
import math
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score


def _arrays(y, p):
    y, p = np.asarray(y, int), np.asarray(p, float)
    if y.ndim != 1 or p.shape != y.shape or not np.isin(y, [0, 1]).all():
        raise ValueError("Invalid binary metric inputs")
    if not np.isfinite(p).all() or ((p < 0) | (p > 1)).any():
        raise ValueError("Nonfinite or out-of-range probability")
    return y, p


def cell_metrics(y, p):
    y, p = _arrays(y, p)
    if not len(y):
        raise ValueError("Empty evaluation cell")
    q = np.clip(p, 1e-7, 1-1e-7)
    ap = float(average_precision_score(y, p)) if y.sum() else float("nan")
    auc = float(roc_auc_score(y, p)) if len(np.unique(y)) == 2 else float("nan")
    bins = np.minimum((p*10).astype(int), 9)
    ece = sum(np.mean(bins == b)*abs(np.mean(y[bins == b])-np.mean(p[bins == b]))
              for b in range(10) if np.any(bins == b))
    return dict(rows=len(y), failures=int(y.sum()), prevalence=float(y.mean()), ap=ap, auc=auc,
                bce=float(-(y*np.log(q)+(1-y)*np.log1p(-q)).mean()),
                brier=float(np.mean((y-p)**2)), ece=float(ece),
                ap_status="DEFINED" if y.sum() else "UNDEFINED_NO_POSITIVES")


def confusion_metrics(y, alerts):
    y, alerts = np.asarray(y, int), np.asarray(alerts, bool)
    tp, fp = int(np.sum(alerts & (y == 1))), int(np.sum(alerts & (y == 0)))
    tn, fn = int(np.sum(~alerts & (y == 0))), int(np.sum(~alerts & (y == 1)))
    precision = tp/(tp+fp) if tp+fp else 0.
    recall = tp/(tp+fn) if tp+fn else float("nan")
    return dict(tp=tp, fp=fp, tn=tn, fn=fn, alerts=int(alerts.sum()),
                alert_fraction=float(alerts.mean()) if len(y) else float("nan"),
                precision=precision, recall=recall,
                f1=2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.,
                f2=5*tp/(5*tp+fp+4*fn) if 5*tp+fp+4*fn else 0.)


def policy_metrics(y, p, threshold):
    y, p = _arrays(y, p)
    if threshold is None or not np.isfinite(threshold):
        return {k: float("nan") for k in ("tp", "fp", "tn", "fn", "alerts", "alert_fraction",
                                         "precision", "recall", "f1", "f2")}
    return confusion_metrics(y, p >= threshold)


def select_threshold(y, p, beta=1):
    y, p = _arrays(y, p)
    empty = dict(threshold=None, objective=f"F{beta}", supporting_rows=len(y),
                 supporting_positives=int(y.sum()), status="UNAVAILABLE")
    if not len(y) or not y.sum():
        return empty
    order = np.argsort(-p, kind="stable")
    score, label = p[order], y[order]
    ends = np.r_[np.flatnonzero(score[:-1] != score[1:]), len(score)-1]
    tp = np.cumsum(label)[ends]
    fp, fn = ends+1-tp, y.sum()-tp
    b2 = float(beta)**2
    f = (1+b2)*tp/np.maximum((1+b2)*tp+fp+b2*fn, 1)
    best = int(np.argmax(f))  # descending thresholds: largest threshold wins ties
    return dict(threshold=float(score[ends[best]]), objective=f"F{beta}",
                supporting_rows=len(y), supporting_positives=int(y.sum()),
                supporting_score=float(f[best]), status="EARLIER_DEVELOPMENT_ONLY")


def budget_alerts(p, row_index, fraction):
    p, row_index = np.asarray(p, float), np.asarray(row_index)
    if p.ndim != 1 or row_index.shape != p.shape or not 0 < fraction <= 1:
        raise ValueError("Invalid fixed-budget inputs")
    if not np.isfinite(p).all() or len(np.unique(row_index)) != len(row_index):
        raise ValueError("Invalid score or duplicate canonical row_index")
    order = np.lexsort((row_index, -p))
    alerts = np.zeros(len(p), bool)
    alerts[order[:min(len(p), int(math.ceil(fraction*len(p))))]] = True
    return alerts


def budget_metrics(y, p, row_index, fraction):
    y, p = _arrays(y, p)
    return dict(budget=float(fraction), **confusion_metrics(y, budget_alerts(p, row_index, fraction)))
