"""icoa_metrics — ready-made metrics for a task's scorer.py. Standard library only.

Every metric takes two lists of the same length, row for row:  metric(pred, truth)
    pred   what the contestant submitted for one column   (strings, as read from the CSV)
    truth  the same column of the labels file

Rules shared with the built-in metrics: a missing, unparseable or non-finite prediction counts as 0;
class names are compared after trimming spaces.

    classes        accuracy  balanced_accuracy  macro_f1  weighted_f1  mcc  f1 (labels 0/1)  qwk (grades)
    probabilities  auc  ap  logloss  brier
    numbers        mse  rmse  mae  rmsle  mape  smape  r2  pearson  spearman  kendall_tau
    several columns / groups of rows
                   joint_accuracy  exact_match  group_kendall_tau
                   all_correct  group_all_correct  by_group
    combining      weighted({"name": (weight, value), ...})
"""
import math

__all__ = [
    "accuracy", "balanced_accuracy", "macro_f1", "weighted_f1", "mcc", "f1", "qwk",
    "auc", "ap", "logloss", "brier",
    "mse", "rmse", "mae", "rmsle", "mape", "smape", "r2", "pearson", "spearman", "kendall_tau",
    "by_group", "all_correct", "joint_accuracy", "group_all_correct", "exact_match",
    "group_kendall_tau", "weighted",
]

_EPS = 2.220446049250313e-16
_INF = float("inf")


# ── reading values ───────────────────────────────────────────────────────────────────────────────────────────
def _s(v):
    return "" if v is None else str(v).strip()


def _num(v):
    """A prediction as a number; missing / unparseable / non-finite = 0.0."""
    try:
        x = float(v)
    except (TypeError, ValueError):
        return 0.0
    return x if math.isfinite(x) else 0.0


def _tnum(v):
    """A label as a number; a label that is not a number is the setter's mistake, so say so."""
    try:
        return float(v)
    except (TypeError, ValueError):
        raise ValueError("label %r is not a number" % (v,)) from None


def _pos(v):
    """True when the value is the number 1 (the positive class of a 0 / 1 label)."""
    try:
        return _s(v) != "" and float(v) == 1.0
    except (TypeError, ValueError):
        return False


def _same_len(pred, truth):
    pred, truth = list(pred), list(truth)
    if len(pred) != len(truth):
        raise ValueError("pred has %d values, truth has %d — they must be the same rows" % (len(pred), len(truth)))
    return pred, truth


def _pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_num(p), _tnum(t)) for p, t in zip(pred, truth)]


def _prob_pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_num(p), 1 if _pos(t) else 0) for p, t in zip(pred, truth)]


def _str_pairs(pred, truth):
    pred, truth = _same_len(pred, truth)
    return [(_s(p), _s(t)) for p, t in zip(pred, truth)]


def _mean_of(pt, f):
    if not pt:
        return _INF
    return sum(f(p, t) for p, t in pt) / len(pt)


# ── classes ──────────────────────────────────────────────────────────────────────────────────────────────────
def accuracy(pred, truth):
    pt = _str_pairs(pred, truth)
    if not pt:
        return 0.0
    return sum(1 for p, t in pt if p == t) / len(pt)


def _per_class(pt):
    out = []
    for lab in sorted(set(t for _, t in pt)):
        tp = sum(1 for p, t in pt if p == lab and t == lab)
        fp = sum(1 for p, t in pt if p == lab and t != lab)
        fn = sum(1 for p, t in pt if p != lab and t == lab)
        out.append((tp, fp, fn))
    return out


def _f1_of(tp, fp, fn):
    denom = 2 * tp + fp + fn
    return 2 * tp / denom if denom else 0.0


def macro_f1(pred, truth):
    cls = _per_class(_str_pairs(pred, truth))
    if not cls:
        return 0.0
    return sum(_f1_of(*c) for c in cls) / len(cls)


def balanced_accuracy(pred, truth):
    cls = _per_class(_str_pairs(pred, truth))
    if not cls:
        return 0.0
    return sum(tp / (tp + fn) for tp, _, fn in cls) / len(cls)


def weighted_f1(pred, truth):
    pt = _str_pairs(pred, truth)
    cls = _per_class(pt)
    if not cls:
        return 0.0
    return sum((tp + fn) * _f1_of(tp, fp, fn) for tp, fp, fn in cls) / len(pt)


def mcc(pred, truth):
    pt = _str_pairs(pred, truth)
    n = len(pt)
    if n == 0:
        return 0.0
    tc, pc, c = {}, {}, 0
    for p, t in pt:
        tc[t] = tc.get(t, 0) + 1
        pc[p] = pc.get(p, 0) + 1
        if p == t:
            c += 1
    cov_tp = c * n - sum(v * pc.get(k, 0) for k, v in tc.items())
    cov_tt = n * n - sum(v * v for v in tc.values())
    cov_pp = n * n - sum(v * v for v in pc.values())
    if cov_tt == 0 or cov_pp == 0:
        return 0.0
    return cov_tp / math.sqrt(cov_tt * cov_pp)


def f1(pred, truth):
    """Labels 0 / 1: F1 of class 1."""
    pred, truth = _same_len(pred, truth)
    tp = fp = fn = 0
    for p, t in zip(pred, truth):
        p, y = _pos(p), _pos(t)
        if p and y:
            tp += 1
        elif p and not y:
            fp += 1
        elif y and not p:
            fn += 1
    return _f1_of(tp, fp, fn)


def qwk(pred, truth):
    """Quadratic weighted kappa: grades span min..max of the labels; a prediction is rounded half-up and clamped."""
    pred, truth = _same_len(pred, truth)
    ts = [int(math.floor(_tnum(t) + 0.5)) for t in truth]
    if not ts:
        return 0.0
    lo, hi = min(ts), max(ts)
    n = hi - lo + 1
    if n < 2:
        return 0.0
    ps = [min(max(int(math.floor(_num(p) + 0.5)), lo), hi) for p in pred]
    ht, hp, obs = [0] * n, [0] * n, 0
    for t, p in zip(ts, ps):
        ht[t - lo] += 1
        hp[p - lo] += 1
        obs += (p - t) ** 2
    exp = sum((i - j) ** 2 * ht[i] * hp[j] for i in range(n) for j in range(n)) / len(ts)
    if exp == 0:
        return 0.0
    return 1 - obs / exp


# ── probabilities (labels 0 / 1, prediction = probability of 1) ──────────────────────────────────────────────
def _ranks(xs):
    """Average ranks, 1-based; ties share the mean of their positions."""
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    out = [0.0] * len(xs)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
            j += 1
        for k in range(i, j + 1):
            out[order[k]] = (i + j) / 2 + 1
        i = j + 1
    return out


def auc(pred, truth):
    pt = _prob_pairs(pred, truth)
    n1 = sum(y for _, y in pt)
    n0 = len(pt) - n1
    if n1 == 0 or n0 == 0:
        return 0.5
    r = _ranks([p for p, _ in pt])
    u = sum(r[i] for i in range(len(pt)) if pt[i][1] == 1) - n1 * (n1 + 1) / 2
    return u / (n1 * n0)


def ap(pred, truth):
    """Average precision (area under the precision-recall curve); tied scores enter together."""
    pt = sorted(_prob_pairs(pred, truth), key=lambda x: -x[0])
    n1 = sum(y for _, y in pt)
    if n1 == 0:
        return 0.0
    total, tp, seen, prev, i = 0.0, 0, 0, 0.0, 0
    while i < len(pt):
        j = i
        while j < len(pt) and pt[j][0] == pt[i][0]:
            tp += pt[j][1]
            seen += 1
            j += 1
        rec = tp / n1
        total += (rec - prev) * (tp / seen)
        prev = rec
        i = j
    return total


def logloss(pred, truth):
    def one(p0, y):
        p = min(max(p0, 1e-15), 1 - 1e-15)
        return -math.log(p) if y == 1 else -math.log(1 - p)

    return _mean_of(_prob_pairs(pred, truth), one)


def brier(pred, truth):
    return _mean_of(_prob_pairs(pred, truth), lambda p, y: (p - y) ** 2)


# ── numbers ──────────────────────────────────────────────────────────────────────────────────────────────────
def mse(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: (p - t) ** 2)


def rmse(pred, truth):
    return math.sqrt(mse(pred, truth))


def mae(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: abs(p - t))


def rmsle(pred, truth):
    return math.sqrt(
        _mean_of(_pairs(pred, truth), lambda p, t: (math.log1p(max(p, 0.0)) - math.log1p(max(t, 0.0))) ** 2)
    )


def mape(pred, truth):
    return _mean_of(_pairs(pred, truth), lambda p, t: abs(p - t) / max(abs(t), _EPS))


def smape(pred, truth):
    def one(p, t):
        d = abs(p) + abs(t)
        return 2 * abs(p - t) / d if d else 0.0

    return _mean_of(_pairs(pred, truth), one)


def r2(pred, truth):
    pt = _pairs(pred, truth)
    if not pt:
        return 0.0
    mean = sum(t for _, t in pt) / len(pt)
    tot = sum((t - mean) ** 2 for _, t in pt)
    if tot == 0:
        return 0.0
    return 1 - sum((p - t) ** 2 for p, t in pt) / tot


def _corr(xs, ys):
    n = len(xs)
    if n == 0:
        return 0.0
    mx, my = sum(xs) / n, sum(ys) / n
    sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
    sxx = sum((x - mx) ** 2 for x in xs)
    syy = sum((y - my) ** 2 for y in ys)
    if sxx == 0 or syy == 0:
        return 0.0
    return sxy / math.sqrt(sxx * syy)


def pearson(pred, truth):
    pt = _pairs(pred, truth)
    return _corr([p for p, _ in pt], [t for _, t in pt])


def spearman(pred, truth):
    pt = _pairs(pred, truth)
    return _corr(_ranks([p for p, _ in pt]), _ranks([t for _, t in pt]))


def kendall_tau(pred, truth, normalised=False):
    """Kendall tau-b (ties handled), -1 .. 1; 0 when either side is constant or there are fewer than 2 rows.
    normalised=True maps it to 0 .. 1 as (tau + 1) / 2."""
    pt = _pairs(pred, truth)
    conc = disc = tie_p = tie_t = 0
    for i in range(len(pt)):
        for j in range(i + 1, len(pt)):
            dp, dt = pt[i][0] - pt[j][0], pt[i][1] - pt[j][1]
            if dp == 0:
                tie_p += 1
            if dt == 0:
                tie_t += 1
            if dp * dt > 0:
                conc += 1
            elif dp * dt < 0:
                disc += 1
    n0 = len(pt) * (len(pt) - 1) // 2
    denom = math.sqrt((n0 - tie_p) * (n0 - tie_t))
    tau = (conc - disc) / denom if denom else 0.0
    return (tau + 1) / 2 if normalised else tau


# ── several columns, groups of rows ──────────────────────────────────────────────────────────────────────────
def _groups(keys):
    """Row numbers of each group, groups in order of first appearance."""
    out = {}
    for i, k in enumerate(keys):
        out.setdefault(_s(k), []).append(i)
    return list(out.values())


def by_group(keys, fn, *columns):
    """Apply fn inside each group of rows and return the mean over groups.
    by_group(truth["week"], mae, pred["mm"], truth["mm"])"""
    keys = list(keys)
    cols = [list(c) for c in columns]
    for c in cols:
        if len(c) != len(keys):
            raise ValueError("by_group: a column has %d values, the keys have %d" % (len(c), len(keys)))
    groups = _groups(keys)
    if not groups:
        return 0.0
    return sum(fn(*[[c[i] for i in rows] for c in cols]) for rows in groups) / len(groups)


def _col_list(cols):
    """Accept one column (a list of values) or a list of columns."""
    cols = list(cols)
    if cols and not isinstance(cols[0], (list, tuple)):
        return [cols]
    return [list(c) for c in cols]


def all_correct(pred_cols, truth_cols):
    """Per row: True when every listed column is right.  all_correct([pred["a"], pred["b"]], [truth["a"], truth["b"]])"""
    pc, tc = _col_list(pred_cols), _col_list(truth_cols)
    if len(pc) != len(tc):
        raise ValueError("all_correct: %d prediction columns against %d label columns" % (len(pc), len(tc)))
    if not pc:
        return []
    for p, t in zip(pc, tc):
        _same_len(p, t)
    return [all(_s(p[i]) == _s(t[i]) for p, t in zip(pc, tc)) for i in range(len(tc[0]))]


def joint_accuracy(pred_cols, truth_cols):
    """Share of rows where every listed column is right."""
    ok = all_correct(pred_cols, truth_cols)
    return sum(ok) / len(ok) if ok else 0.0


def group_all_correct(keys, pred_cols, truth_cols):
    """Share of groups in which every row is right in every listed column."""
    ok = all_correct(pred_cols, truth_cols)
    keys = list(keys)
    if len(keys) != len(ok):
        raise ValueError("group_all_correct: the keys have %d values, the columns have %d" % (len(keys), len(ok)))
    groups = _groups(keys)
    if not groups:
        return 0.0
    return sum(1 for rows in groups if all(ok[i] for i in rows)) / len(groups)


exact_match = group_all_correct


def group_kendall_tau(keys, pred, truth, normalised=True):
    """Kendall tau inside each group, mean over groups (0 .. 1 by default)."""
    return by_group(keys, lambda p, t: kendall_tau(p, t, normalised=normalised), pred, truth)


# ── combining ────────────────────────────────────────────────────────────────────────────────────────────────
def weighted(parts):
    """weighted({"rain": (0.6, 0.81), "amount": (0.4, 0.55)}) -> {"score": 0.706, "parts": {...}}
    The weights must add up to 1."""
    if not parts:
        raise ValueError("weighted: give at least one part")
    total = 0.0
    score = 0.0
    values = {}
    for name, pair in parts.items():
        try:
            w, v = pair
            w, v = float(w), float(v)
        except (TypeError, ValueError):
            raise ValueError('weighted: part "%s" must be (weight, value), two numbers' % name) from None
        total += w
        score += w * v
        values[str(name)] = v
    if abs(total - 1.0) > 1e-9:
        raise ValueError("weighted: the weights add up to %.6g — they must add up to 1" % total)
    return {"score": score, "parts": values}
