"""
Solution: rubric design. Lab 08's agreement and validity math (evalkit/agreement.py and Scripts 1-4).
Standard library only.
"""

CATEGORIES = [
    ("invented fact", ["never said", "made up", "come from", "not in convo"]),
    ("wrong detail", ["amount is wrong", "wrong number", "doesn't match"]),
    ("missing order ID / amounts", ["order number", "which order", "order #"]),
    ("missed a request", ["forgot", "drops", "missing"]),
    ("no next step", ["what happens next", "next step", "action"]),
    ("judgmental tone", ["difficult", "rude", "blames", "snippy", "judgy", "tone"]),
    ("padding / repetition", ["repeats", "rambling", "wordy"]),
    ("fine", ["fine", "good", "ok", "clear"]),
]


def categorize(note):
    low = note.lower()
    for name, keys in CATEGORIES:
        if any(k in low for k in keys):
            return name
    return "uncategorized"


def _pairs(a, b):
    if len(a) != len(b):
        raise ValueError("both labelers must label the same items")
    return [(bool(x), bool(y)) for x, y in zip(a, b)]


def agreement_counts(a, b):
    p = _pairs(a, b)
    return {"both_pass": sum(x and y for x, y in p), "only_a": sum(x and not y for x, y in p),
            "only_b": sum(y and not x for x, y in p), "both_fail": sum(not x and not y for x, y in p)}


def percent_agreement(a, b):
    p = _pairs(a, b)
    return sum(x == y for x, y in p) / len(p)


def chance_agreement(a, b):
    p = _pairs(a, b)
    pa = sum(x for x, _ in p) / len(p)
    pb = sum(y for _, y in p) / len(p)
    return pa * pb + (1 - pa) * (1 - pb)


def cohen_kappa(a, b):
    po = percent_agreement(a, b)
    pe = chance_agreement(a, b)
    if pe >= 1.0:
        return 1.0 if po == 1.0 else 0.0
    return (po - pe) / (1 - pe)


def rating_gap(passed, ratings):
    yes = [r for p, r in zip(passed, ratings) if p]
    no = [r for p, r in zip(passed, ratings) if not p]
    if not yes or not no:
        return None
    return sum(yes) / len(yes) - sum(no) / len(no)


def length_groups(words, ratings, padded, limit=50):
    groups = {"short": [], "useful": [], "padded": []}
    for w, r, pad in zip(words, ratings, padded):
        key = "short" if w <= limit else ("padded" if pad else "useful")
        groups[key].append(r)
    return {k: (len(v), sum(v) / len(v) if v else None) for k, v in groups.items()}


def labels_changed(before, after):
    return sum(bool(x) != bool(y) for x, y in _pairs(before, after))
