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


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


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


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


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


def margin(accuracy, shuffles):
    """How far the accuracy is above chance: accuracy minus the average shuffled accuracy."""
    # TODO
    raise NotImplementedError


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


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


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


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