"""
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."""
    # TODO
    raise NotImplementedError


def lcs_length(a, b):
    """Length of the longest common subsequence of two word lists (same words, same order, gaps allowed)."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


def faithfulness(summary, source):
    """Share of split_claims(summary) that claim_supported() accepts. 1.0 if there are no claims."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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]"""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError
