"""Tests on Lab 09's recorded data (eval labs, Metrics Without a Reference Answer). Everything is simulated: the
chats, the summaries, their planted flaws and the team lead's ratings. Nia's summary B is the lab's summary with a
made-up sentence; summary A is the lab's own rewording function applied to her reference answer. Tom's summary is
flawless; the damaged versions are the lab's perturbations of it.
Run: pytest test_metrics_practice.py"""
from metrics_practice import (checker_rates, claim_supported, coverage, faithfulness, ranks, rouge_1, rouge_l,
                              spearman)

NIA_CHAT = "Customer: Hi, this is Nia. My Merino Beanie (order #63369) stopped working after a week.\nAgent: Sorry to hear that, Nia. Let me look at order #63369.\nCustomer: Also, I'm moving, so please change the delivery address to Reno. I'd like a refund of $120. I also need an invoice for my expense report. It was a birthday gift for my daughter.\nAgent: Understood. I'll take care of it: update the address before the parcel ships; refund of $120 to be issued (3–5 days); email the invoice.\nCustomer: Thanks."
NIA_REFERENCE = 'Nia (order #63369, Merino Beanie): item stopped working after a week. Customer wants the address changed to Reno, and wants a refund of $120, and needs an invoice copy. It was a birthday gift. Next step: update the address before the parcel ships; refund of $120 to be issued (3–5 days); email the invoice.'
NIA_B = 'Nia (order #63369, Merino Beanie): item stopped working after a week. Customer wants the address changed to Reno, and wants a refund of $120, and needs an invoice copy. It was a birthday gift. Customer says this is their first order with us. Next step: update the address before the parcel ships; refund of $120 to be issued (3–5 days); email the invoice.'
NIA_A = 'Order #63369 (Merino Beanie, for Nia): stopped working after a week. Requests: new delivery address: Reno; refund of $120; invoice copy. It was a birthday gift. Action: update the address before the parcel ships; refund of $120 to be issued (3–5 days); email the invoice.'
NIA_FACTS = [{'fact': 'order number', 'must_contain': ['63369']}, {'fact': 'request: address', 'must_contain': ['Reno']}, {'fact': 'request: refund', 'must_contain': ['refund', '$120']}, {'fact': 'request: invoice', 'must_contain': ['invoice']}, {'fact': 'context: gift', 'must_contain': ['gift']}]
TOM_CHAT = "Customer: Hi, this is Tom. My Alpine Fleece (order #65046) arrived damaged. The box was crushed.\nAgent: Sorry to hear that, Tom. Let me look at order #65046.\nCustomer: I'd like a refund of $120. Also, I'm moving, so please change the delivery address to Denver.\nAgent: Understood. I'll take care of it: refund of $120 to be issued (3–5 days); update the address before the parcel ships.\nCustomer: Thanks."
TOM = 'Tom (order #65046, Alpine Fleece): item arrived damaged. Customer wants a refund of $120, and wants the address changed to Denver. Next step: refund of $120 to be issued (3–5 days); update the address before the parcel ships.'
TOM_FACTS = [{'fact': 'order number', 'must_contain': ['65046']}, {'fact': 'request: refund', 'must_contain': ['refund', '$120']}, {'fact': 'request: address', 'must_contain': ['Denver']}]
SAM_CHAT = "Customer: Hi, this is Sam. My Canvas Tote (order #60049) came in the wrong size. This is really frustrating!\nAgent: Sorry to hear that, Sam. Let me look at order #60049.\nCustomer: Can someone tell me where the package actually is?\nAgent: Understood. I'll take care of it: carrier trace opened; update the customer within 48 hours.\nCustomer: Thanks."
SAM = 'Sam (order #60049, Canvas Tote): item arrived in the wrong size. Customer wants a tracking update. Next step: carrier trace opened; update the customer within 48 hours.'
# All 120 summaries: (the lead's 1-5 rating, ROUGE-1, faithfulness, coverage, what the summary really contains),
# scores rounded to 4 decimals. "factual" = a planted made-up fact or wrong detail; "other" = only a judgmental remark
# or padding (also unsupported by the chat, but not a factual error); "true" = every claim is true.
SCORES = [
    (1, 0.65, 0.5, 0.75, "factual"),
    (5, 1.0, 1.0, 1.0, "true"),
    (5, 0.8421, 1.0, 1.0, "true"),
    (3, 1.0, 1.0, 1.0, "true"),
    (5, 1.0, 1.0, 1.0, "true"),
    (1, 0.8732, 0.3333, 0.6667, "factual"),
    (3, 0.8387, 0.75, 0.75, "true"),
    (2, 0.641, 1.0, 0.75, "true"),
    (5, 0.7945, 0.8333, 0.75, "true"),
    (2, 0.6173, 0.8, 0.5, "true"),
    (3, 0.8222, 0.6, 0.75, "true"),
    (4, 0.8085, 1.0, 1.0, "true"),
    (3, 0.8814, 0.8333, 0.8, "true"),
    (3, 0.6739, 1.0, 0.8, "true"),
    (4, 0.8409, 0.8571, 1.0, "true"),
    (1, 0.7273, 0.3333, 0.3333, "factual"),
    (5, 1.0, 0.8333, 1.0, "true"),
    (5, 0.7677, 0.875, 1.0, "true"),
    (5, 1.0, 0.8333, 1.0, "true"),
    (3, 0.8986, 1.0, 0.6667, "true"),
    (5, 0.88, 0.75, 1.0, "true"),
    (5, 0.7191, 1.0, 0.75, "true"),
    (2, 0.8, 1.0, 0.6667, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 0.764, 0.8, 1.0, "true"),
    (4, 0.8434, 1.0, 1.0, "true"),
    (1, 0.5385, 0.3333, 0.3333, "factual"),
    (3, 0.9474, 0.75, 0.75, "true"),
    (4, 1.0, 0.8333, 1.0, "true"),
    (5, 0.75, 0.75, 1.0, "true"),
    (2, 0.8941, 0.8333, 0.5, "factual"),
    (5, 1.0, 0.875, 1.0, "true"),
    (4, 1.0, 0.875, 1.0, "true"),
    (5, 0.8525, 0.875, 1.0, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (3, 0.7045, 1.0, 0.75, "true"),
    (4, 0.7619, 0.75, 1.0, "true"),
    (4, 1.0, 0.875, 1.0, "true"),
    (3, 0.7302, 1.0, 0.6667, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 0.8, 1.0, 1.0, "true"),
    (3, 0.9231, 0.8571, 0.75, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 0.75, 1.0, "true"),
    (3, 0.9136, 1.0, 0.6667, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (3, 0.7541, 1.0, 1.0, "true"),
    (4, 0.7636, 1.0, 1.0, "true"),
    (3, 0.8485, 1.0, 0.75, "true"),
    (4, 0.8052, 1.0, 0.75, "true"),
    (3, 0.7887, 0.75, 0.6667, "other"),
    (4, 0.9286, 0.6, 1.0, "other"),
    (3, 0.9244, 0.7778, 1.0, "factual"),
    (2, 0.963, 0.625, 0.75, "factual"),
    (4, 0.74, 1.0, 1.0, "true"),
    (3, 0.8132, 0.6667, 0.75, "factual"),
    (3, 0.92, 0.8571, 1.0, "factual"),
    (3, 0.8315, 0.75, 0.75, "true"),
    (3, 0.6769, 1.0, 0.6667, "true"),
    (2, 0.9268, 0.875, 1.0, "factual"),
    (5, 1.0, 0.8571, 1.0, "true"),
    (4, 0.7955, 1.0, 1.0, "true"),
    (4, 0.8986, 0.8, 1.0, "other"),
    (5, 1.0, 0.8889, 1.0, "true"),
    (4, 0.6422, 0.8571, 1.0, "other"),
    (3, 0.7879, 1.0, 0.75, "true"),
    (3, 0.9683, 0.625, 0.8, "factual"),
    (1, 0.7473, 0.6, 1.0, "factual"),
    (1, 0.885, 0.375, 0.75, "factual"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 0.8333, 1.0, "true"),
    (2, 0.8966, 0.8333, 1.0, "factual"),
    (1, 0.6197, 0.75, 0.6667, "other"),
    (4, 0.8364, 1.0, 1.0, "true"),
    (4, 1.0, 0.875, 1.0, "true"),
    (3, 0.8627, 0.8571, 0.8, "true"),
    (3, 0.9706, 0.75, 0.6667, "factual"),
    (5, 1.0, 0.8333, 1.0, "true"),
    (3, 0.866, 0.8333, 0.75, "true"),
    (4, 0.764, 0.6, 1.0, "true"),
    (4, 0.9123, 1.0, 0.6667, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 0.8, 0.75, 1.0, "true"),
    (5, 0.7792, 1.0, 1.0, "true"),
    (3, 0.7683, 0.6364, 1.0, "other"),
    (4, 1.0, 0.8333, 1.0, "true"),
    (5, 0.8226, 0.875, 1.0, "true"),
    (3, 0.6857, 0.5, 1.0, "true"),
    (5, 0.75, 1.0, 1.0, "true"),
    (3, 0.9655, 0.6667, 0.8, "factual"),
    (2, 0.9365, 0.875, 1.0, "factual"),
    (5, 0.7921, 0.7143, 0.75, "true"),
    (3, 0.6835, 0.6667, 0.75, "true"),
    (3, 0.9032, 0.75, 1.0, "other"),
    (3, 0.6364, 1.0, 0.5, "true"),
    (4, 0.8182, 0.7143, 1.0, "factual"),
    (4, 0.9524, 0.8889, 1.0, "other"),
    (4, 0.8333, 1.0, 1.0, "true"),
    (2, 0.9011, 0.8333, 1.0, "factual"),
    (4, 0.7619, 1.0, 1.0, "true"),
    (3, 0.5301, 0.75, 1.0, "other"),
    (4, 0.9, 0.6, 1.0, "other"),
    (2, 0.7347, 0.6667, 0.75, "other"),
    (5, 1.0, 0.75, 1.0, "true"),
    (3, 0.8049, 0.6667, 0.75, "true"),
    (2, 0.8762, 0.7143, 0.75, "factual"),
    (5, 1.0, 0.875, 1.0, "true"),
    (2, 0.9804, 0.7143, 0.75, "factual"),
    (4, 1.0, 1.0, 1.0, "true"),
    (4, 0.5432, 0.8, 1.0, "true"),
    (2, 0.4828, 1.0, 0.6667, "true"),
    (4, 0.9412, 1.0, 0.8, "true"),
    (5, 0.8824, 0.75, 1.0, "true"),
    (2, 0.9688, 0.6, 0.6667, "factual"),
    (3, 0.9655, 0.5, 0.8, "factual"),
    (4, 1.0, 1.0, 1.0, "true"),
]


def close(a, b, tol=0.0005):
    return a is not None and abs(a - b) < tol


def test_rouge_rewards_the_copy_with_a_made_up_fact():
    assert close(rouge_1(NIA_B, NIA_REFERENCE), 0.9244)   # 55 shared words, 64 vs 55: 110 / 119
    assert close(rouge_1(NIA_A, NIA_REFERENCE), 0.8119)   # 41 shared words, 46 vs 55: 82 / 101
    assert rouge_1(NIA_B, NIA_REFERENCE) > rouge_1(NIA_A, NIA_REFERENCE)
    assert rouge_1(NIA_REFERENCE, NIA_REFERENCE) == 1.0
    assert rouge_1("", NIA_REFERENCE) == 0.0
    assert rouge_1("hello world", NIA_REFERENCE) == 0.0


def test_rouge_l_counts_order():
    assert close(rouge_l(NIA_B, NIA_REFERENCE), 0.9244)
    assert close(rouge_l(NIA_A, NIA_REFERENCE), 0.7921)
    reordered = ("Tom (order #65046, Alpine Fleece): item arrived damaged. Next step: refund of $120 to be issued "
                 "(3–5 days); update the address before the parcel ships. Customer wants a refund of $120, and wants "
                 "the address changed to Denver.")
    assert rouge_1(reordered, TOM) == 1.0          # same words
    assert close(rouge_l(reordered, TOM), 0.6667)  # different order


def test_the_claim_checker():
    assert claim_supported("Customer wants the address changed to Reno", NIA_CHAT)
    assert not claim_supported("Customer says this is their first order with us", NIA_CHAT)  # made up: caught
    assert not claim_supported("needs an invoice copy", NIA_CHAT)        # true, but "copy" isn't in the chat
    assert not claim_supported("Customer wants a tracking update", SAM_CHAT)  # true: "where is the package?"
    assert not claim_supported("Customer wants a refund of $135", TOM_CHAT)   # a number not in the chat
    assert claim_supported("Customer does not want a refund of $120", TOM_CHAT)  # the negation slips through


def test_faithfulness():
    assert close(faithfulness(NIA_B, NIA_CHAT), 7 / 9)
    assert close(faithfulness(NIA_A, NIA_CHAT), 7 / 8)
    assert faithfulness(TOM, TOM_CHAT) == 1.0
    assert close(faithfulness(TOM.replace("$120", "$135"), TOM_CHAT), 0.6)
    assert faithfulness(TOM.replace("Customer wants ", "Customer does not want ", 1), TOM_CHAT) == 1.0
    assert close(faithfulness(SAM, SAM_CHAT), 0.75)
    assert faithfulness("", NIA_CHAT) == 1.0


def test_coverage():
    assert coverage(NIA_B, NIA_FACTS) == 1.0   # coverage can't see the made-up sentence
    assert coverage(NIA_A, NIA_FACTS) == 1.0
    assert close(coverage(NIA_B.replace("Reno", "Denver"), NIA_FACTS), 0.8)
    assert close(coverage(TOM.replace("$120", "$135"), TOM_FACTS), 2 / 3)
    assert coverage(TOM, []) == 1.0
    facts = [{"fact": "request: tracking", "must_contain": ["tracking|delivery"]}]
    assert coverage("an update on the delivery", facts) == 1.0


def test_ranks_average_ties():
    assert ranks([10, 30, 20, 20]) == [1.0, 4.0, 2.5, 2.5]
    assert ranks([5, 5, 5]) == [2.0, 2.0, 2.0]


def test_spearman_against_the_lead():
    assert close(spearman([1, 2, 3, 4], [10, 20, 30, 40]), 1.0)
    assert close(spearman([1, 2, 3, 4], [4, 3, 2, 1]), -1.0)
    assert spearman([1, 1, 1], [1, 2, 3]) is None
    rating = [s[0] for s in SCORES]
    assert close(spearman([s[3] for s in SCORES], rating), 0.6180, 0.001)   # coverage
    assert close(spearman([s[2] for s in SCORES], rating), 0.3455, 0.001)   # faithfulness
    assert close(spearman([s[1] for s in SCORES], rating), 0.3196, 0.001)   # ROUGE-1
    assert close(spearman([s[2] * s[3] for s in SCORES], rating), 0.6059, 0.001)  # faithfulness x coverage


def test_grading_the_checker():
    flagged = [s[2] < 1 for s in SCORES]
    assert sum(flagged) == 75
    groups = [s[4] for s in SCORES]
    assert groups.count("factual") == 23 and groups.count("other") == 11 and groups.count("true") == 86
    keep = [i for i, g in enumerate(groups) if g != "other"]
    catch, false_alarm = checker_rates([flagged[i] for i in keep], [groups[i] == "factual" for i in keep])
    assert catch == 1.0                         # 23 of 23 made-up facts and wrong details
    assert close(false_alarm, 41 / 86)          # 41 of 86 all-true summaries: 48%
    assert all(flagged[i] for i, g in enumerate(groups) if g == "other")   # all 11 flagged, fairly
    assert checker_rates([True, False], [True, True]) == (0.5, None)
