"""
Practice: scores without a reference answer. Lab 09's text metrics (evalkit/textmetrics.py): ROUGE-1 and
ROUGE-L (words shared with a reference answer), the offline claim checker, faithfulness (the share of claims the
chat supports), coverage (the share of must-have facts present), Spearman's rank correlation (does a score order
summaries the way a person does?), and the checker's own catch rate and false-alarm rate.

Fill in the TODOs, then run the tests:
    pytest test_metrics_practice.py      (locally)
or press "Run tests" on the chapter page.

words(), stem(), STOPWORDS and split_claims() are given: they are the lab's exact tokenizing rules, so your
scores match the lab's to the last digit. Standard library only.
"""
import re

STOPWORDS = set("""a an the and or but if of to for in on at by with from as is are was were be been being it its
this that these those i you he she they we them his her their our your my me us customer customers wants want
wanted needs need has have had will would can could should do does did not no so also just than then there here
about into over after before once up out what which who whom when where why how all any each some more most very
item next step steps request requests action""".split())


def words(text):
    """Lower-case words, numbers, $amounts and #ids, as the lab tokenizes them."""
    return re.findall(r"[a-z0-9$#]+(?:\.[0-9]+)?", text.lower())


def stem(w):
    """Trim a common ending (ing, ed, es, s) from words longer than 4 letters."""
    for suffix in ("ing", "ed", "es", "s"):
        if len(w) > 4 and w.endswith(suffix):
            return w[: -len(suffix)]
    return w


def split_claims(text):
    """Sentences, further split on ', and', ';' and ' and wants' so each request is its own claim."""
    parts = re.split(r"(?<=[.!?])\s+|;\s*|,\s+and\s+|\s+and\s+(?=wants|needs)", text.strip())
    return [p.strip(" .") for p in parts if len(words(p)) >= 2]


def rouge_1(candidate, reference):
    """F1 of shared words, counting repeats: shared = sum over words of min(count in candidate, count in reference).
    precision = shared / candidate words, recall = shared / reference words, F1 = 2PR / (P + R)
    (which equals 2 * shared / (candidate words + reference words)). Return 0.0 if either is empty or nothing is shared."""
    c, r = words(candidate), words(reference)
    if not c or not r:
        return 0.0
    shared = sum(min(c.count(w), r.count(w)) for w in set(c))
    if shared == 0:
        return 0.0
    return 2 * shared / (len(c) + len(r))


def lcs_length(a, b):
    """Length of the longest common subsequence of two word lists (same words, same order, gaps allowed)."""
    prev = [0] * (len(b) + 1)
    for x in a:
        cur = [0]
        for j, y in enumerate(b, start=1):
            cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1]))
        prev = cur
    return prev[-1]


def rouge_l(candidate, reference):
    """Like ROUGE-1, but 'shared' is the longest common subsequence of words, so order matters:
    F1 = 2 * lcs / (candidate words + reference words). Return 0.0 if either is empty or lcs is 0."""
    c, r = words(candidate), words(reference)
    if not c or not r:
        return 0.0
    lcs = lcs_length(c, r)
    return 2 * lcs / (len(c) + len(r)) if lcs else 0.0


def claim_supported(claim, source, min_share=0.6):
    """The lab's offline checker. A claim is supported if
    1. every number in it (digits, like 120 or 63369) appears in the source, and
    2. at least min_share of its content words appear in the source, after stem() on both sides.
    Content words: words(claim) that are not in STOPWORDS and are not pure digits.
    A claim with no content words (and no missing numbers) is supported."""
    src_words = {stem(w) for w in words(source)}
    src_numbers = set(re.findall(r"\d+(?:\.\d+)?", source))
    if not set(re.findall(r"\d+(?:\.\d+)?", claim)) <= src_numbers:
        return False
    content = [stem(w) for w in words(claim) if w not in STOPWORDS and not w.isdigit()]
    if not content:
        return True
    return sum(w in src_words for w in content) / len(content) >= min_share


def faithfulness(summary, source):
    """Share of split_claims(summary) that claim_supported() accepts. 1.0 if there are no claims."""
    claims = split_claims(summary)
    if not claims:
        return 1.0
    return sum(claim_supported(c, source) for c in claims) / len(claims)


def coverage(summary, facts):
    """Share of must-have facts present. Each fact is {"fact": label, "must_contain": [tokens]}; it is present when
    every token appears in the summary (case-insensitive substring). A token may list alternatives with '|'
    ("tracking|delivery"): any one of them counts. 1.0 if there are no facts."""
    if not facts:
        return 1.0
    low = summary.lower()
    present = [all(any(alt.lower() in low for alt in tok.split("|")) for tok in f["must_contain"]) for f in facts]
    return sum(present) / len(facts)


def ranks(xs):
    """Ranks 1..n from smallest to largest; tied values share the average of their ranks.
    ranks([10, 30, 20, 20]) == [1.0, 4.0, 2.5, 2.5]"""
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    r = [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):
            r[order[k]] = (i + j) / 2 + 1
        i = j + 1
    return r


def spearman(x, y):
    """Spearman's rank correlation: the ordinary (Pearson) correlation of ranks(x) and ranks(y).
    1 = same order, 0 = unrelated, -1 = opposite. Return None if either has no spread."""
    rx, ry = ranks(x), ranks(y)
    n = len(rx)
    mx, my = sum(rx) / n, sum(ry) / n
    sxy = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
    sxx = sum((a - mx) ** 2 for a in rx)
    syy = sum((b - my) ** 2 for b in ry)
    if sxx == 0 or syy == 0:
        return None
    return sxy / (sxx * syy) ** 0.5


def checker_rates(flagged, has_error):
    """Grade the grader. flagged[i]: the checker flagged summary i (faithfulness < 1). has_error[i]: summary i really
    contains a false claim (known here because the flaws are planted).
    Return (catch_rate, false_alarm_rate): the share of real errors flagged, and the share of all-true summaries
    flagged. Use None for a rate whose group is empty."""
    err = [f for f, e in zip(flagged, has_error) if e]
    ok = [f for f, e in zip(flagged, has_error) if not e]
    catch = sum(err) / len(err) if err else None
    false_alarm = sum(ok) / len(ok) if ok else None
    return catch, false_alarm
