import bisect
import json
import random
from datetime import datetime, timedelta, timezone


DAY = 86400


def _window(rng, ctx, duration):
    first = rng.randint(3, 13 - duration)
    return ctx["month_start"][first], ctx["month_start"][first + duration]


def _segments(payload, delimiter):
    return [segment.split("|" if delimiter == "\r" else "*")
            for segment in payload.split(delimiter)]


def _join(segments, delimiter):
    separator = "|" if delimiter == "\r" else "*"
    return delimiter.join(separator.join(fields) for fields in segments)


def _segment(segments, tag, qualifier=None):
    for fields in segments:
        if fields[0] == tag:
            if qualifier is None or (len(fields) > 1 and fields[1] == qualifier):
                return fields
    return None


def _hl7_time(value):
    return datetime.strptime(value, "%Y%m%d%H%M%S%z")


def _replace_payload(envelope, payload):
    return {**envelope, "payload": payload}


def _month_boundaries(ctx):
    return [ctx["month_start"][m] for m in range(1, 16)]


def _month(timestamp, boundaries):
    month = bisect.bisect_right(boundaries, timestamp)
    return month if 1 <= month <= 14 else None


def _month_last_date(ctx, month):
    # Toronto month starts fall on the same calendar date in UTC.
    next_start = datetime.fromtimestamp(
        ctx["month_start"][month + 1], timezone.utc
    ).date()
    return next_start - timedelta(days=1)


def lab_unit_upgrade(envelopes, rng, ctx):
    """The analyzer converts cholesterol values but the interface retains mg/dL."""
    start, end = _window(rng, ctx, 5)
    source = rng.choice(["lab-north", "lab-central", "lab-south"])
    out = []
    for e in envelopes:
        if e["feed"] == "lab" and e["source"] == source:
            segments = _segments(e["payload"], "\r")
            obr = _segment(segments, "OBR")
            if obr and len(obr) > 7:
                draw = _hl7_time(obr[7]).timestamp()
                if start <= draw < end:
                    changed = False
                    for fields in segments:
                        if (fields[0] == "OBX" and len(fields) > 6
                                and fields[3].split("^")[0]
                                in {"13457-7", "2093-3"}):
                            fields[5] = f"{float(fields[5]) / 38.67:.2f}"
                            # OBX-6 and the reference range retain the old units.
                            changed = True
                    if changed:
                        e = _replace_payload(e, _join(segments, "\r"))
        out.append(e)
    return out


def device_numeric_identity(envelopes, rng, ctx):
    """A new gateway stores a persistent cohort's MRNs as decimal integers."""
    start, end = _window(rng, ctx, 6)
    cohort = {}
    out = []
    for e in envelopes:
        if e["feed"] == "device" and start <= e["arrived"] < end:
            obj = json.loads(e["payload"])
            identifier = obj["subject"]["identifier"]
            mrn = identifier["value"]
            if mrn not in cohort:
                cohort[mrn] = rng.random() < 0.35
            if cohort[mrn] and mrn.isdigit():
                identifier["value"] = str(int(mrn))
                e = _replace_payload(e, json.dumps(obj, separators=(",", ":")))
        out.append(e)
    return out


def device_store_and_forward(envelopes, rng, ctx):
    """A gateway buffers ten days of readings until after monthly publication."""
    start, end = _window(rng, ctx, 3)
    boundaries = _month_boundaries(ctx)
    out = []
    for e in envelopes:
        if e["feed"] == "device" and start <= e["arrived"] < end:
            obj = json.loads(e["payload"])
            effective = datetime.fromisoformat(obj["effectiveDateTime"])
            month = _month(effective.timestamp(), boundaries)
            if month is not None and 8 <= effective.day <= 17:
                release = ctx["month_start"][month + 1] + 5 * DAY
                e = {**e, "arrived": max(e["arrived"], release)}
        out.append(e)
    return out


def enrollment_termination_file_missing(envelopes, rng, ctx):
    """A file split sends most terminations to a directory the receiver omits."""
    start, end = _window(rng, ctx, 5)
    out = []
    for e in envelopes:
        if e["feed"] == "enroll" and start <= e["arrived"] < end:
            segments = _segments(e["payload"], "~")
            ins = _segment(segments, "INS")
            if ins and len(ins) > 3 and ins[3] == "024":
                if rng.random() < 0.70:
                    continue
        out.append(e)
    return out


def enrollment_month_end_rounding(envelopes, rng, ctx):
    """An export option rounds termination dates to the end of their month."""
    start, end = _window(rng, ctx, 6)
    out = []
    for e in envelopes:
        if e["feed"] == "enroll" and start <= e["arrived"] < end:
            segments = _segments(e["payload"], "~")
            ins = _segment(segments, "INS")
            dtp = _segment(segments, "DTP", "349")
            if (ins and len(ins) > 3 and ins[3] == "024"
                    and dtp and len(dtp) > 3):
                old = datetime.strptime(dtp[3], "%Y%m%d")
                next_month = (old.replace(day=28) + timedelta(days=4)).replace(day=1)
                dtp[3] = (next_month - timedelta(days=1)).strftime("%Y%m%d")
                e = _replace_payload(e, _join(segments, "~"))
        out.append(e)
    return out


def claims_transmission_date_mapping(envelopes, rng, ctx):
    """A clearinghouse maps the interchange date into the service-date element."""
    start, end = _window(rng, ctx, 4)
    out = []
    for e in envelopes:
        if e["feed"] == "claims" and start <= e["arrived"] < end:
            if rng.random() < 0.80:
                segments = _segments(e["payload"], "~")
                gs = _segment(segments, "GS")
                dtp = _segment(segments, "DTP", "472")
                if gs and len(gs) > 4 and dtp and len(dtp) > 3:
                    dtp[3] = gs[4]
                    e = _replace_payload(e, _join(segments, "~"))
        out.append(e)
    return out


def clinic_event_mapping(envelopes, rng, ctx):
    """A clinic upgrade emits encounter updates instead of visit notifications."""
    start, end = _window(rng, ctx, 5)
    source = rng.choice(["adt-north", "adt-central", "adt-south"])
    out = []
    for e in envelopes:
        if (e["feed"] == "adt" and e["source"] == source
                and start <= e["arrived"] < end):
            segments = _segments(e["payload"], "\r")
            msh = _segment(segments, "MSH")
            if msh and len(msh) > 9 and msh[9] == "ADT^A04":
                msh[9] = "ADT^A08"
                evn = _segment(segments, "EVN")
                if evn and len(evn) > 1:
                    evn[1] = "A08"
                e = _replace_payload(e, _join(segments, "\r"))
        out.append(e)
    return out


def consent_portal_identifier(envelopes, rng, ctx):
    """A portal prefixes MRNs without updating the identifier namespace."""
    start, end = _window(rng, ctx, 6)
    out = []
    for e in envelopes:
        if e["feed"] == "consent" and start <= e["arrived"] < end:
            if rng.random() < 0.75:
                obj = json.loads(e["payload"])
                identifier = obj["patient"]["identifier"]
                identifier["value"] = "PORTAL-" + identifier["value"]
                e = _replace_payload(e, json.dumps(obj, separators=(",", ":")))
        out.append(e)
    return out


def lab_utc_clock_with_local_offset(envelopes, rng, ctx):
    """An instrument writes UTC clock digits while retaining its local offset."""
    start, end = _window(rng, ctx, 4)
    source = rng.choice(["lab-north", "lab-central", "lab-south"])
    out = []
    for e in envelopes:
        if e["feed"] == "lab" and e["source"] == source:
            segments = _segments(e["payload"], "\r")
            obr = _segment(segments, "OBR")
            if obr and len(obr) > 7:
                original = _hl7_time(obr[7])
                if start <= original.timestamp() < end:
                    for fields in segments:
                        index = 7 if fields[0] == "OBR" else (
                            14 if fields[0] == "OBX" else None
                        )
                        if index is not None and len(fields) > index and fields[index]:
                            value = _hl7_time(fields[index])
                            fields[index] = (
                                value.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S")
                                + value.strftime("%z")
                            )
                    e = _replace_payload(e, _join(segments, "\r"))
        out.append(e)
    return out


def lab_result_column_swap(envelopes, rng, ctx):
    """A vendor mapping reverses the LDL and total-cholesterol result columns."""
    start, end = _window(rng, ctx, 3)
    source = rng.choice(["lab-north", "lab-central", "lab-south"])
    out = []
    for e in envelopes:
        if e["feed"] == "lab" and e["source"] == source:
            segments = _segments(e["payload"], "\r")
            obr = _segment(segments, "OBR")
            if obr and len(obr) > 7:
                if start <= _hl7_time(obr[7]).timestamp() < end:
                    results = {
                        fields[3].split("^")[0]: fields
                        for fields in segments
                        if fields[0] == "OBX" and len(fields) > 5
                    }
                    ldl = results.get("13457-7")
                    total = results.get("2093-3")
                    if ldl is not None and total is not None:
                        ldl[5], total[5] = total[5], ldl[5]
                        e = _replace_payload(e, _join(segments, "\r"))
        out.append(e)
    return out


# Effect sizes are rough hypotheses, not guarantees about an unseen platform.
# Identity resolution, validation, deduplication and actual cohort sizes can
# reduce or prevent an effect. Percentage-point estimates are platform-wide.
FAULTS = [
    {
        "id": "B01",
        "name": "Analyzer unit upgrade",
        "feeds": ["lab"],
        "what_breaks": (
            "One site's analyzer changes cholesterol numbers to mmol/L for five "
            "months, while its HL7 interface continues labeling them mg/dL."
        ),
        "expected_effect": (
            "LDL control rises, roughly 10 to 25 percentage points if the site "
            "contributes about a third of panels and the mislabeled values are accepted."
        ),
        "apply": lab_unit_upgrade,
    },
    {
        "id": "B02",
        "name": "Numeric gateway MRNs",
        "feeds": ["device"],
        "what_breaks": (
            "A six-month gateway rollout stores MRNs numerically for a persistent "
            "35% cohort, removing leading zeroes from their Observation identifiers."
        ),
        "expected_effect": (
            "Monitoring adherence falls if unpadded identifiers fail to link. "
            "A loss around 10 to 30 percentage points is plausible with a fixed denominator."
        ),
        "apply": device_numeric_identity,
    },
    {
        "id": "B03",
        "name": "Gateway buffer outage",
        "feeds": ["device"],
        "what_breaks": (
            "For three months, readings from the 8th through the 17th remain in "
            "a gateway buffer until five days into the following month."
        ),
        "expected_effect": (
            "Monitoring adherence falls at publication, plausibly 10 to 40 percentage "
            "points depending on how many people sit near the 16-day threshold."
        ),
        "apply": device_store_and_forward,
    },
    {
        "id": "B04",
        "name": "Missing termination partition",
        "feeds": ["enroll"],
        "what_breaks": (
            "An enrollment export splits terminations into another file partition. "
            "The receiver misses 70% of termination interchanges for five months."
        ),
        "expected_effect": (
            "Active enrolled members increase as terminated spans stay open, "
            "potentially about 1 to 8% by the end of the fault window."
        ),
        "apply": enrollment_termination_file_missing,
    },
    {
        "id": "B05",
        "name": "Month end termination dates",
        "feeds": ["enroll"],
        "what_breaks": (
            "A six-month export configuration rounds every termination end date "
            "to the final calendar day of its original month."
        ),
        "expected_effect": (
            "Active enrolled members increase when actual coverage ended before "
            "the 15th, plausibly around 0.5 to 3% in affected months."
        ),
        "apply": enrollment_month_end_rounding,
    },
    {
        "id": "B06",
        "name": "Claims date mapping",
        "feeds": ["claims"],
        "what_breaks": (
            "During a four-month clearinghouse migration, 80% of claims carry "
            "their transmission date in DTP*472 instead of their service date."
        ),
        "expected_effect": (
            "The 30-day follow-up rate is expected to fall by roughly 2 to 10 "
            "percentage points as delayed claims move beyond the follow-up window; "
            "some formerly out-of-window services can move into a window."
        ),
        "apply": claims_transmission_date_mapping,
    },
    {
        "id": "B07",
        "name": "Clinic event upgrade",
        "feeds": ["adt"],
        "what_breaks": (
            "One site's clinic upgrade sends A08 patient updates for five months "
            "where it previously sent A04 outpatient visit notifications."
        ),
        "expected_effect": (
            "The 30-day follow-up rate falls if these updates no longer establish "
            "visits, plausibly 3 to 15 percentage points after outside claims offset some losses."
        ),
        "apply": clinic_event_mapping,
    },
    {
        "id": "B08",
        "name": "Portal consent identifiers",
        "feeds": ["consent"],
        "what_breaks": (
            "For six months, 75% of withdrawal messages use a portal-prefixed MRN "
            "while still declaring the original MRN identifier namespace."
        ),
        "expected_effect": (
            "Missed withdrawals inflate active member counts by the affected "
            "withdrawn-member count, plausibly under 1 to 3%. Rate metrics retain "
            "those people and may shift either way, typically less than a few points."
        ),
        "apply": consent_portal_identifier,
    },
    {
        "id": "B09",
        "name": "Instrument clock configuration",
        "feeds": ["lab"],
        "what_breaks": (
            "For four months at one site, collection and observation timestamps "
            "contain UTC clock digits followed by the original Toronto offset, "
            "making draws appear four or five hours later."
        ),
        "expected_effect": (
            "LDL panels shift from month end into the next month. Control can "
            "rise or fall depending on those panels and last-result ordering; "
            "the platform-wide change is expected to be small, usually under 1 percentage point."
        ),
        "apply": lab_utc_clock_with_local_offset,
    },
    {
        "id": "B10",
        "name": "Reversed lipid result columns",
        "feeds": ["lab"],
        "what_breaks": (
            "A vendor mapping edit swaps the LDL and total-cholesterol value "
            "columns at one site for three months, retaining their original codes and units."
        ),
        "expected_effect": (
            "LDL control falls because total-cholesterol values are interpreted "
            "as LDL, plausibly 10 to 25 percentage points with a roughly equal site mix."
        ),
        "apply": lab_result_column_swap,
    },
]
