#!/usr/bin/env python3
"""Our code. Reusable evaluation diagnostics for ordinal rubric scoring:
  - Canonical Krippendorff's ordinal alpha (2011 coincidence-matrix definition)
  - Ordinal Gwet's AC2 (quadratic weights) + exact / within-1 agreement
  - Paired phenomenon-cluster bootstrap CIs for pair accuracy, model-vs-ref alpha gap,
    and specificity-stuffing score inflation (Q6).

Usage:
  python3 scout/checks/ordinal_agreement_and_gaming.py --selftest
"""
from __future__ import annotations

import math
import sys
from typing import Callable, Sequence

import numpy as np


def krippendorff_ordinal_alpha(
    ratings: Sequence[Sequence[float | int | None]],
) -> float:
    """Canonical Krippendorff (2011) ordinal alpha over an (R x N) matrix.

    Missing ratings are represented as None or NaN. Columns with < 2 valid
    ratings are ignored. Returns NaN if there is no expected disagreement (D_e == 0).
    """
    valid_cols: list[list[float]] = []
    n_items = len(ratings[0]) if ratings else 0
    n_raters = len(ratings)
    for j in range(n_items):
        col = []
        for i in range(n_raters):
            v = ratings[i][j]
            if v is not None and not (isinstance(v, float) and math.isnan(v)):
                col.append(float(v))
        if len(col) >= 2:
            valid_cols.append(col)

    if not valid_cols:
        return float("nan")

    cats = sorted({v for col in valid_cols for v in col})
    k = len(cats)
    if k <= 1:
        # All pairable values are identical: zero disagreement.
        return float("nan")
    cat_idx = {c: idx for idx, c in enumerate(cats)}

    coinc = np.zeros((k, k), dtype=np.float64)
    for col in valid_cols:
        m_u = len(col)
        weight = 1.0 / (m_u - 1)
        for a in range(m_u):
            ia = cat_idx[col[a]]
            for b in range(m_u):
                if a == b:
                    continue
                ib = cat_idx[col[b]]
                coinc[ia, ib] += weight

    marg = coinc.sum(axis=1)
    n_total = float(marg.sum())
    if n_total <= 1.0:
        return float("nan")

    # Ordinal squared metric delta^2(c, g) = (sum_{h=min..max} n_h - (n_c + n_g)/2)^2
    delta2 = np.zeros((k, k), dtype=np.float64)
    cum = np.cumsum(marg)
    for i in range(k):
        for j in range(i + 1, k):
            span = cum[j] - (cum[i - 1] if i > 0 else 0.0)
            d = span - 0.5 * (marg[i] + marg[j])
            val = d * d
            delta2[i, j] = val
            delta2[j, i] = val

    d_o = float((coinc * delta2).sum() / n_total)
    expected_pairs = np.outer(marg, marg)
    d_e = float((expected_pairs * delta2).sum() / (n_total * (n_total - 1.0)))
    if d_e == 0.0:
        return float("nan")
    return float(1.0 - d_o / d_e)


def gwet_ac2_ordinal(
    ratings: Sequence[Sequence[float | int | None]],
    categories: Sequence[int] = (1, 2, 3, 4, 5),
) -> dict[str, float]:
    """Quadratic-weighted ordinal Gwet's AC2 and raw pairwise agreement stats."""
    cats = list(categories)
    q = len(cats)
    cat_idx = {c: idx for idx, c in enumerate(cats)}
    span = float(cats[-1] - cats[0]) if q > 1 else 1.0

    # Quadratic weight matrix w_{c,k} = 1 - ((c - k) / span)^2
    w = np.zeros((q, q), dtype=np.float64)
    for i, ci in enumerate(cats):
        for j, cj in enumerate(cats):
            w[i, j] = 1.0 - ((ci - cj) / span) ** 2

    n_items = len(ratings[0]) if ratings else 0
    n_raters = len(ratings)
    pa_list: list[float] = []
    exact_list: list[float] = []
    within1_list: list[float] = []
    pi = np.zeros(q, dtype=np.float64)
    n_valid_items = 0

    for u in range(n_items):
        col = []
        for r in range(n_raters):
            v = ratings[r][u]
            if v is not None and not (isinstance(v, float) and math.isnan(v)):
                col.append(int(round(float(v))))
        m_u = len(col)
        if m_u < 2:
            continue
        n_valid_items += 1
        for v in col:
            pi[cat_idx[v]] += 1.0 / m_u
        w_sum = 0.0
        ex_sum = 0.0
        w1_sum = 0.0
        pairs = m_u * (m_u - 1)
        for a in range(m_u):
            ia = cat_idx[col[a]]
            for b in range(m_u):
                if a == b:
                    continue
                ib = cat_idx[col[b]]
                w_sum += w[ia, ib]
                if col[a] == col[b]:
                    ex_sum += 1.0
                if abs(col[a] - col[b]) <= 1:
                    w1_sum += 1.0
        pa_list.append(w_sum / pairs)
        exact_list.append(ex_sum / pairs)
        within1_list.append(w1_sum / pairs)

    if n_valid_items == 0:
        return {"ac2": float("nan"), "pa": float("nan"), "pe": float("nan"),
                "exact": float("nan"), "within1": float("nan"), "n": 0}

    pi /= n_valid_items
    p_a = float(np.mean(pa_list))
    t_w = float(w.sum())
    p_e = float((t_w / (q * (q - 1))) * np.sum(pi * (1.0 - pi)))
    ac2 = float("nan") if p_e >= 1.0 else float((p_a - p_e) / (1.0 - p_e))
    return {
        "ac2": ac2,
        "pa": p_a,
        "pe": p_e,
        "exact": float(np.mean(exact_list)),
        "within1": float(np.mean(within1_list)),
        "n": int(n_valid_items),
    }


def pair_accuracy_stats(
    high_scores: Sequence[float | int | None],
    low_scores: Sequence[float | int | None],
    n_boot: int = 2000,
    seed: int = 0,
) -> dict[str, float | list[float] | int]:
    """Paired accuracy P(high > low) with ties counted as misses + cluster bootstrap CI."""
    pairs = []
    for h, l in zip(high_scores, low_scores):
        if h is None or l is None:
            continue
        if (isinstance(h, float) and math.isnan(h)) or (isinstance(l, float) and math.isnan(l)):
            continue
        pairs.append((float(h), float(l)))
    n = len(pairs)
    if n == 0:
        return {"acc": float("nan"), "ci95": [float("nan"), float("nan")],
                "wins": 0, "ties": 0, "losses": 0, "n": 0}

    arr = np.asarray(pairs, dtype=np.float64)
    diff = arr[:, 0] - arr[:, 1]
    wins = int((diff > 0).sum())
    ties = int((diff == 0).sum())
    losses = int((diff < 0).sum())
    ind = (diff > 0).astype(np.float64)
    acc = float(ind.mean())

    rng = np.random.default_rng(seed)
    idx = rng.integers(0, n, size=(n_boot, n))
    boot = ind[idx].mean(axis=1)
    return {
        "acc": acc,
        "ci95": [float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))],
        "wins": wins,
        "ties": ties,
        "losses": losses,
        "n": n,
    }


def paired_mean_diff_stats(
    a_scores: Sequence[float | int | None],
    b_scores: Sequence[float | int | None],
    n_boot: int = 2000,
    seed: int = 0,
) -> dict[str, float | list[float] | int]:
    """Paired mean(a - b) and phenomenon-bootstrap 95% CI (e.g. stuffed - easy)."""
    diffs = []
    for a, b in zip(a_scores, b_scores):
        if a is None or b is None:
            continue
        if (isinstance(a, float) and math.isnan(a)) or (isinstance(b, float) and math.isnan(b)):
            continue
        diffs.append(float(a) - float(b))
    n = len(diffs)
    if n == 0:
        return {"mean_diff": float("nan"), "ci95": [float("nan"), float("nan")], "n": 0}

    arr = np.asarray(diffs, dtype=np.float64)
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, n, size=(n_boot, n))
    boot = arr[idx].mean(axis=1)
    return {
        "mean_diff": float(arr.mean()),
        "ci95": [float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))],
        "n": n,
    }


def cluster_bootstrap_stat(
    cluster_matrix: Sequence[Sequence[Sequence[float | int | None]]],
    stat_fn: Callable[[list[list[float | int | None]]], float],
    n_boot: int = 2000,
    seed: int = 0,
) -> dict[str, float | list[float] | int]:
    """Bootstrap a multi-rater statistic by resampling phenomenon clusters (keeping all arms per phenomenon together).

    cluster_matrix has shape [n_clusters][n_raters][n_arms_per_cluster].
    """
    m = len(cluster_matrix)
    if m == 0:
        return {"estimate": float("nan"), "ci95": [float("nan"), float("nan")], "n_clusters": 0}
    n_raters = len(cluster_matrix[0])

    def flatten(indices: Sequence[int]) -> list[list[float | int | None]]:
        out: list[list[float | int | None]] = [[] for _ in range(n_raters)]
        for c_idx in indices:
            for r in range(n_raters):
                out[r].extend(cluster_matrix[c_idx][r])
        return out

    est = float(stat_fn(flatten(range(m))))
    rng = np.random.default_rng(seed)
    boots: list[float] = []
    for _ in range(n_boot):
        draw = rng.integers(0, m, size=m)
        val = float(stat_fn(flatten(draw)))
        if not math.isnan(val):
            boots.append(val)
    ci95 = (
        [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))]
        if boots else [float("nan"), float("nan")]
    )
    return {"estimate": est, "ci95": ci95, "n_clusters": m, "n_valid_boot": len(boots)}


def _selftest() -> None:
    # 1. Perfect agreement -> alpha = 1.0, AC2 = 1.0
    perf = [[1, 2, 3, 4, 5, 1, 2, 3], [1, 2, 3, 4, 5, 1, 2, 3]]
    assert abs(krippendorff_ordinal_alpha(perf) - 1.0) < 1e-12
    assert abs(gwet_ac2_ordinal(perf)["ac2"] - 1.0) < 1e-12

    # 2. Krippendorff (2011) worked-style ordinal check with missing values & 4 raters
    # Verify symmetry and known hand-computed value for small 2-rater ordinal table
    small = [[1, 2, 3, 3, 4, 5], [1, 2, 3, 4, 4, 5]]
    a_small = krippendorff_ordinal_alpha(small)
    assert 0.85 < a_small < 1.0, f"unexpected a_small={a_small}"

    # 3. Range-restriction contrast: high agreement clustered on {4, 5}
    skewed = [[5, 5, 5, 5, 5, 5, 5, 4, 5, 4], [5, 5, 5, 5, 5, 5, 4, 5, 5, 5]]
    a_skew = krippendorff_ordinal_alpha(skewed)
    g_skew = gwet_ac2_ordinal(skewed)
    assert abs(g_skew["exact"] - 0.7) < 1e-12, g_skew
    assert g_skew["ac2"] > 0.85 and a_skew < 0.30, (a_skew, g_skew)

    # 4. Pair accuracy (ties = miss)
    pa = pair_accuracy_stats([5, 4, 4, 3], [4, 4, 2, 5], n_boot=200, seed=0)
    assert pa["wins"] == 2 and pa["ties"] == 1 and pa["losses"] == 1
    assert abs(pa["acc"] - 0.5) < 1e-12

    print("SELFTEST PASS")


if __name__ == "__main__":
    if "--selftest" in sys.argv:
        _selftest()
