"""The semantic contracts S1 to S10 (DESIGN.md), as functions the pipeline calls. Every threshold is declared here.

Written by the same hand as the declared faults, so a catch of a declared fault is a self-test."""
import re
from statistics import median

# S1 identifier formats
MRN_RE = re.compile(r"^\d{8}$")
MEMBER_RE = re.compile(r"^M\d{9}$")

# S2 identity matching
W = dict(given_hi=2.5, given_mid=1.0, given_no=-1.5, fam_hi=3.0, fam_mid=1.0, fam_no=-2.0, dob_eq=4.0, dob_near=1.5,
         dob_no=-4.0, sex_eq=0.5, sex_no=-1.0, zip_eq=1.5, zip_no=0.0)
JW_HI, JW_MID = 0.92, 0.80
LINK, REVIEW = 8.0, 5.5
NICKNAMES = {"katherine": "kate", "catherine": "kate", "kathleen": "kathy", "elizabeth": "liz", "margaret": "peggy",
             "patricia": "pat", "susan": "sue", "jennifer": "jen", "rebecca": "becky", "victoria": "vicky",
             "robert": "bob", "william": "bill", "richard": "rick", "michael": "mike", "joseph": "joe",
             "anthony": "tony", "matthew": "matt", "daniel": "dan", "edward": "ed", "thomas": "tom",
             "samuel": "sam", "james": "jim", "christopher": "chris", "nicholas": "nick", "andrew": "andy",
             "alexander": "alex", "benjamin": "ben", "jonathan": "jon", "deborah": "deb", "barbara": "barb",
             "jessica": "jess", "stephanie": "steph", "christine": "chris", "theodore": "ted", "gregory": "greg"}

# S3 units and plausible ranges (after conversion to the metric's unit)
MGDL_PER_MMOL_CHOL = 38.67
UNIT_PROPERTY = {"13457-7": "mass", "18262-6": "mass", "22748-8": "moles", "2093-3": "mass", "8480-6": "pressure"}
UNITS = {"mass": {"mg/dL"}, "moles": {"mmol/L"}, "pressure": {"mmHg", "mm[Hg]"}}
RANGE = {"13457-7": (15, 400), "18262-6": (15, 400), "22748-8": (15, 400), "2093-3": (70, 500), "8480-6": (60, 260)}

# S4 code sets
LAB_CODES = {"13457-7", "18262-6", "22748-8", "2093-3"}
LOCAL_MAP = {"LDL": "13457-7", "CHOL": "2093-3"}
DEVICE_CODES = {"8480-6"}

# S5 drift, S6 time, S7 completeness, S8 spans
DRIFT_SHIFT, DRIFT_MIN_N, DRIFT_MONTHS = 0.12, 30, 3
FUTURE_TOLERANCE_S = 600
GAP_RATIO, GAP_REF_DAYS, GAP_MIN_REF = 0.30, 28, 5
CLAIMS_SHARE = 0.85
SPAN_SHARE = 0.003


def norm_mrn(s):
    """S1: returns (key or None, changed)."""
    s = (s or "").strip()
    if MRN_RE.match(s):
        return s, False
    if s.isdigit() and len(s) < 8:
        return s.zfill(8), True
    return None, False


def norm_member(s):
    s = (s or "").strip().upper()
    if MEMBER_RE.match(s):
        return s, False
    if s.isdigit() and len(s) == 9:
        return "M" + s, True
    return None, False


def jaro_winkler(a, b):
    if a == b:
        return 1.0
    la, lb = len(a), len(b)
    if not la or not lb:
        return 0.0
    rng = max(la, lb) // 2 - 1
    am, bm = [False] * la, [False] * lb
    m = 0
    for i in range(la):
        lo, hi = max(0, i - rng), min(i + rng + 1, lb)
        for j in range(lo, hi):
            if not bm[j] and a[i] == b[j]:
                am[i] = bm[j] = True
                m += 1
                break
    if not m:
        return 0.0
    t, k = 0, 0
    for i in range(la):
        if am[i]:
            while not bm[k]:
                k += 1
            if a[i] != b[k]:
                t += 1
            k += 1
    j = (m / la + m / lb + (m - t / 2) / m) / 3
    p = 0
    for x, y in zip(a[:4], b[:4]):
        if x != y:
            break
        p += 1
    return j + p * 0.1 * (1 - j)


def _given(a, b):
    a, b = a.lower(), b.lower()
    if a == b or NICKNAMES.get(a) == b or NICKNAMES.get(b) == a:
        return 1.0
    return jaro_winkler(a, b)


def _dob(a, b):
    if a is None or b is None:
        return "no"
    if a == b:
        return "eq"
    if a.year == b.year and a.month == b.day and a.day == b.month:
        return "near"
    sa, sb = a.strftime("%Y%m%d"), b.strftime("%Y%m%d")
    if sum(x != y for x, y in zip(sa, sb)) == 1:
        return "near"
    return "no"


def score(x, y):
    """x, y: dicts with giv, fam, dob, sex, zip. Max 11.5."""
    g = _given(x["giv"], y["giv"])
    f = jaro_winkler(x["fam"].lower(), y["fam"].lower())
    s = W["given_hi"] if g >= JW_HI else W["given_mid"] if g >= JW_MID else W["given_no"]
    s += W["fam_hi"] if f >= JW_HI else W["fam_mid"] if f >= JW_MID else W["fam_no"]
    s += W["dob_" + _dob(x["dob"], y["dob"])]
    s += W["sex_eq"] if x["sex"] == y["sex"] else W["sex_no"]
    s += W["zip_eq"] if x["zip"] and x["zip"] == y["zip"] else W["zip_no"]
    return s


def soundex(name):
    name = re.sub(r"[^A-Z]", "", (name or "").upper())
    if not name:
        return ""
    codes = {**dict.fromkeys("BFPV", "1"), **dict.fromkeys("CGJKQSXZ", "2"), **dict.fromkeys("DT", "3"), "L": "4",
             **dict.fromkeys("MN", "5"), "R": "6"}
    out, last = name[0], codes.get(name[0], "")
    for ch in name[1:]:
        c = codes.get(ch, "")
        if c and c != last:
            out += c
        if ch not in "HW":
            last = c
    return (out + "000")[:4]


def blocks(rec):
    yield ("dob", rec["dob"])
    yield ("sx", soundex(rec["fam"].split("-")[0]), rec["zip"])


def lab_value(code, unit, value):
    """S3 and S4 for one lab result. Returns (code, mg/dL value or None, action, reason). action: ok, fix, quarantine."""
    if code not in LAB_CODES:
        return code, None, "quarantine", "code not in value set"
    prop = UNIT_PROPERTY[code]
    if value is None:
        return code, None, "quarantine", "no value"
    if unit in UNITS["mass"]:
        v, action = value, ("ok" if prop == "mass" else "fix")
    elif unit in UNITS["moles"]:
        v, action = value * MGDL_PER_MMOL_CHOL, ("ok" if prop == "moles" else "fix")
    else:
        return code, None, "quarantine", "unit not allowed"
    lo, hi = RANGE[code]
    if not lo <= v <= hi:
        return code, None, "quarantine", "out of range"
    return code, v, action, "unit disagrees with code" if action == "fix" else ""


def drift(cur, ref):
    """S5: True if the median of `cur` moved more than the declared share from the median of `ref`."""
    if len(cur) < DRIFT_MIN_N or len(ref) < DRIFT_MIN_N:
        return False
    r = median(ref)
    return r > 0 and abs(median(cur) / r - 1) > DRIFT_SHIFT
