"""
Practice: same rules, different form. Lab 16's offline math (policy.py, common.py,
02_compare.py, evalkit/stats.py): the rules engine that gives every case its exact right
answer, the path and depth of a case, putting a wrong answer down to one flipped decision,
reading the model's answer, and the numbers the lab compares forms with.

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

The policy and the 150 cases are made up; the model answers in the tests are real recorded
runs (gpt-5.4-nano, two runs per case and form). Nothing here calls a model.
Rates and differences are fractions (0.713, not 71.3).
"""
import json
import math
import re

Z_95 = 1.959963984540054
OUTCOMES = ["FULL_REFUND", "PARTIAL_REFUND", "REPLACEMENT", "STORE_CREDIT", "REFUSE"]

# The refund policy as a rule tree (policy.py's TREE): each decision is
# (question, test, yes-branch, no-branch); a branch is another decision or an outcome.
# A case is a dict: days, state ("unopened" / "opened" / "damaged" / "defective"),
# price, member, prior_refund (a refund in the last 90 days), final_sale.
TREE = (
    "Final-sale item?", lambda c: c["final_sale"],
    ("Arrived damaged?", lambda c: c["state"] == "damaged", "REPLACEMENT", "REFUSE"),
    ("Arrived damaged or defective?", lambda c: c["state"] in ("damaged", "defective"),
     ("Delivered 90 days ago or less?", lambda c: c["days"] <= 90,
      ("Price over $200?", lambda c: c["price"] > 200, "REPLACEMENT", "FULL_REFUND"),
      "STORE_CREDIT"),
     ("Delivered 30 days ago or less?", lambda c: c["days"] <= 30,
      ("Opened?", lambda c: c["state"] == "opened",
       ("Refund in the last 90 days?", lambda c: c["prior_refund"],
        "STORE_CREDIT",
        ("Member?", lambda c: c["member"], "FULL_REFUND", "PARTIAL_REFUND")),
       "FULL_REFUND"),
      ("Member and delivered 60 days ago or less?", lambda c: c["member"] and c["days"] <= 60,
       "STORE_CREDIT", "REFUSE"))),
)


def path(case, flip=None):
    """Walk TREE for one case. Return (steps, outcome): steps is a list of
    (question, answer) for every decision passed, top to bottom; outcome is the label
    reached. With flip=<question>, that one decision is answered the other way."""
    steps, node = [], TREE
    while isinstance(node, tuple):
        question, test, yes, no = node
        answer = bool(test(case))
        if question == flip:
            answer = not answer
        steps.append((question, answer))
        node = yes if answer else no
    return steps, node


def decide(case, flip=None):
    """The right outcome for a case (the rules engine), or, with flip=<question>,
    the outcome if that one decision were answered wrongly."""
    return path(case, flip)[1]


def depth(case):
    """How many decisions the case passes through (2 to 6 in this tree)."""
    return len(path(case)[0])


def flip_explains(case, wrong):
    """The questions on the case's path whose single flip gives `wrong`, top to bottom.
    An empty list means no single wrong decision explains that answer."""
    return [q for q, _ in path(case)[0] if decide(case, flip=q) == wrong]


def blame(case, got):
    """Lab 16's attribution of one wrong answer: the DEEPEST question in
    flip_explains(case, got) (a convention), or "none" if there is none or got is "INVALID"."""
    if got == "INVALID":
        return "none"
    qs = flip_explains(case, got)
    return qs[-1] if qs else "none"


def parse_outcome(text):
    """The model's answer label (common.py). Try JSON first: take its "outcome" value.
    If the text isn't JSON (or not a JSON object), take the first of the five labels found
    anywhere in the text. Then uppercase, strip, replace spaces with underscores; return it
    if it's one of OUTCOMES, else "INVALID"."""
    try:
        val = json.loads(text).get("outcome", "")
    except (json.JSONDecodeError, AttributeError):
        m = re.search("|".join(OUTCOMES), text or "")
        val = m.group(0) if m else ""
    val = str(val).strip().upper().replace(" ", "_")
    return val if val in OUTCOMES else "INVALID"


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 mcnemar_p(a_only, b_only):
    """Exact two-sided McNemar p-value for a paired comparison. a_only: cases only A got
    right; b_only: cases only B got right. With n = a_only + b_only and k = the smaller one:
    min(1, 2 * sum(C(n, i) for i in 0..k) / 2^n). 1.0 when n == 0."""
    n = a_only + b_only
    if n == 0:
        return 1.0
    k = min(a_only, b_only)
    return min(1.0, 2 * sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n)


def paired_mean_diff(runs_a, runs_b):
    """Paired difference in accuracy, form A minus form B (02_compare.py). runs_a and
    runs_b map case id -> list of right/wrong (True/False) answers, one per run. Average
    each case's runs first, then take the mean over cases of (A's average - B's average)."""
    ids = sorted(runs_a)
    return sum(sum(runs_a[i]) / len(runs_a[i]) - sum(runs_b[i]) / len(runs_b[i]) for i in ids) / len(ids)


def aa_flips(runs):
    """A/A check: how many cases get a different verdict when the same form is asked
    again (run 0 vs run 1). runs maps case id -> [run 0 right?, run 1 right?]."""
    return sum(r[0] != r[1] for r in runs.values())


def cost_per_1k_correct(total_cost, right):
    """What 1,000 RIGHT answers cost: 1000 * total_cost / right (right at least 1)."""
    return 1000 * total_cost / max(right, 1)
