"""
Solution: the pieces behind Lab 10's review metrics (see metrics_practice.py for the task).
"""

import math
import re
import statistics

REVERT_REF = re.compile(r"\brevert(?:s|ed)?`?\s+(?:of\s+)?(?:https://github\.com/[\w.-]+/[\w.-]+/pull/|[\w.-]+/[\w.-]+#|#)(\d+)", re.I)
REVERT_WORD = re.compile(r"\brevert(?:s|ed)?\b", re.I)

TALK = ("comment", "thread", "CHANGES_REQUESTED", "COMMENTED")


def silent_approval(events: list[tuple[str, str, str]], author: str) -> bool:
    people = [(who, action) for who, account, action in events if account == "human" and who != author]
    approved = any(action == "APPROVED" for _, action in people)
    talked = any(action in TALK for _, action in people)
    return approved and not talked


def revert_target(title: str, body: str, titles: dict[str, int]) -> int | None:
    if not (REVERT_WORD.search(title) or REVERT_REF.search(body)):
        return None
    m = REVERT_REF.search(title + "\n" + body)
    if m:
        return int(m.group(1))
    t = re.search(r'revert\s+"(.+)"', title, re.I)
    return titles.get(t.group(1)) if t else None


def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
    if n == 0:
        return (0.0, 1.0)
    p = k / n
    d = 1 + z**2 / n
    centre = (p + z**2 / (2 * n)) / d
    half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / d
    return (max(0.0, centre - half), min(1.0, centre + half))


def shifted(before: list[float], after: list[float], z: float = 2.0) -> int:
    if len(before) < 2 or not after:
        raise ValueError("need at least two before-weeks and one after-week")
    mb, ma = statistics.mean(before), statistics.mean(after)
    vb = statistics.variance(before)
    va = statistics.variance(after) if len(after) > 1 else vb
    se = (vb / len(before) + va / len(after)) ** 0.5
    if se == 0:
        return 0 if ma == mb else (1 if ma > mb else -1)
    t = (ma - mb) / se
    return 1 if t > z else -1 if t < -z else 0


def first_notice(series: list[float], switch: int, max_after: int = 13) -> int | None:
    for k in range(1, max_after + 1):
        if shifted(series[:switch], series[switch:switch + k]) != 0:
            return k
    return None
