"""
Practice: is your synthetic data realistic? Lab 12's math (evalkit/realism.py,
evalkit/dataset.py, evalkit/stats.py, common.py, 02_c2st.py, 03_score_gap.py,
04_usage_rule.py): text features, word overlap for near-twins, the simulated summarizer's
rule, the classifier test's two baselines, ranges for a score gap, reweighting to the real
mix, and the usage rule per group.

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

Everything in Lab 12 is simulated: "real" tickets stand in for real customer traffic.
Rates, shares and gaps are fractions (0.705, not 70.5).
"""
import math
import re

Z_95 = 1.959963984540054


def features(text):
    """A few of Lab 12's readable features of one ticket, from the text alone:
    words             number of words (runs of letters and apostrophes, [A-Za-zÀ-ÿ']+)
    starts_lowercase  1.0 if the first character is a lowercase letter, else 0.0
    has_order_number  1.0 if the text contains '#' then optional space then digits, else 0.0
    politeness        how many words (lowercased) are please / thank / thanks / appreciate
    asks              1 + how many times the word 'also' appears (any case): issues in one ticket
    All values are floats."""
    words = re.findall(r"[A-Za-zÀ-ÿ']+", text)
    low = [w.lower() for w in words]
    return {
        "words": float(len(words)),
        "starts_lowercase": float(bool(text) and text[0].islower()),
        "has_order_number": float(bool(re.search(r"#\s?\d+", text))),
        "politeness": float(sum(low.count(w) for w in ("please", "thank", "thanks", "appreciate"))),
        "asks": float(1 + len(re.findall(r"\balso\b", text, flags=re.I))),
    }


def jaccard(a, b):
    """Word overlap of two texts: shared words / all distinct words. Normalize first: lowercase,
    replace every run of digits with '#', keep the tokens matching [a-z0-9#]+. Two empty texts
    score 1.0. Lab 12 calls two tickets near-twins at 0.6 or more."""
    def words(t):
        return set(re.findall(r"[a-z0-9#]+", re.sub(r"\d+", "#", t.lower())))
    sa, sb = words(a), words(b)
    if not sa and not sb:
        return 1.0
    return len(sa & sb) / len(sa | sb)


def pass_probability(issues, mood, has_order, typos, spanish):
    """The simulated summarizer's chance of a correct summary (common.py). A logit:
    2.2 - 0.7 per issue beyond the first - 0.6 if angry - 0.3 if frustrated
        - 0.6 without an order number - 0.15 per typo (at most 4 count) - 1.0 if Spanish,
    then 1 / (1 + e^-logit)."""
    logit = (2.2 - 0.7 * (issues - 1) - 0.6 * (mood == "angry") - 0.3 * (mood == "frustrated")
             - 0.6 * (not has_order) - 0.15 * min(typos, 4) - 1.0 * bool(spanish))
    return 1 / (1 + math.exp(-logit))


def majority_baseline(n_a, n_b):
    """Accuracy of always guessing the bigger of two sets: max(n_a, n_b) / (n_a + n_b)."""
    return max(n_a, n_b) / (n_a + n_b)


def permutation_p(accuracy, shuffles):
    """p-value of the classifier test: (1 + how many shuffled-label accuracies are at least
    `accuracy`) / (1 + number of shuffles)."""
    return (1 + sum(s >= accuracy for s in shuffles)) / (1 + len(shuffles))


def margin(accuracy, shuffles):
    """How far the accuracy is above chance: accuracy minus the average shuffled accuracy."""
    return accuracy - sum(shuffles) / len(shuffles)


def wilson_ci(passes, n, z=Z_95):
    """Wilson interval (low, high) for a pass rate; (0.0, 1.0) when n == 0.
    center = (p + z^2/(2n)) / (1 + z^2/n),  half = z * sqrt(p(1-p)/n + z^2/(4n^2)) / (1 + z^2/n);
    clip to [0, 1]."""
    if n == 0:
        return 0.0, 1.0
    p = passes / n
    denom = 1 + z * z / n
    center = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return max(0.0, center - half), min(1.0, center + half)


def newcombe_diff_ci(passes_a, n_a, passes_b, n_b, z=Z_95):
    """Range (low, high) for rate_b - rate_a (pa = passes_a / n_a, pb = passes_b / n_b), measured
    on DIFFERENT cases (Newcombe's method,
    from the two Wilson intervals (la, ua) and (lb, ub)):
    low  = d - sqrt((pb - lb)^2 + (ua - pa)^2),  high = d + sqrt((ub - pb)^2 + (pa - la)^2)."""
    pa, pb = passes_a / n_a, passes_b / n_b
    la, ua = wilson_ci(passes_a, n_a, z)
    lb, ub = wilson_ci(passes_b, n_b, z)
    d = pb - pa
    return (d - math.sqrt((pb - lb) ** 2 + (ua - pa) ** 2),
            d + math.sqrt((ub - pb) ** 2 + (pa - la) ** 2))


def reweighted(cells, rate):
    """The synthetic set's score reweighted to the real mix: the sum over cells of
    (real tickets in the cell / all real tickets) * rate(cell).
    cells: a list of dicts with at least 'nr' (real tickets in the cell); rate: a function
    of a cell, e.g. lambda c: c['kd'] / c['nd'] (measured) or lambda c: c['td'] (true).
    Skip cells with no synthetic tickets ('nd' == 0)."""
    total = sum(c["nr"] for c in cells)
    return sum(c["nr"] / total * rate(c) for c in cells if c["nd"] > 0)


def usage_rule(n_real, n_syn, margin, gap):
    """Lab 12's rule for one group (04_usage_rule.py). margin: classifier accuracy above its
    shuffled baseline; gap: synthetic pass rate minus real (both fractions). In order:
    no synthetic tickets              -> "coverage gap"
    fewer than 20 real or synthetic   -> "too few to judge"
    margin < 0.05 and |gap| < 0.03    -> "measure"
    |gap| < 0.05                      -> "find failures, measure on real"
    otherwise                         -> "find failures only" """
    if n_syn == 0:
        return "coverage gap"
    if n_real < 20 or n_syn < 20:
        return "too few to judge"
    if margin < 0.05 and abs(gap) < 0.03:
        return "measure"
    if abs(gap) < 0.05:
        return "find failures, measure on real"
    return "find failures only"
