"""The checks of each arm (DESIGN.md, "Arms"): the pre-release contract (plain and extended), the landed monitors,
the semantic landed checks and the dashboard reader. Thresholds are parameters so the sensitivity runs can move them."""
import math
from collections import Counter

from .emit import DAY, Change, Emitter
from .measure import LINK_EVENTS, METRICS, READ_LAG
from .plan import apply_plan_ops, base_plan, violations

DEFAULTS = {"vol_lo": 0.7, "vol_hi": 1.4, "vol_min": 20, "fail_share": 0.01, "fail_min": 5, "unplanned_min": 20,
            "metric_k": 3.0, "dash": 0.30, "trail": 28, "txn_share": 0.01, "txn_min": 2, "link_drop": 0.05,
            "fast_rise": 0.15}


# ---------- the contract ----------

class ScriptWorld:
    """The world a scripted test runs in: a few devices with known signups and sessions."""

    def __init__(self):
        self.platform, self.install_day, self.signup_t, self.method, self.sessions = [], [], {}, {}, {}

    def add_user(self, platform, install_day):
        self.platform.append(platform)
        self.install_day.append(install_day)
        return len(self.platform) - 1

    def next_session(self, uid, t):
        later = [s for s in self.sessions.get(uid, ()) if s > t]
        return min(later) if later else None


def scripts(release_day, extended, salt=0):
    """Scripted sessions (DESIGN.md arm 3, and arm 5 when extended). Returns (world, [(name, actions)]).
    salt shifts the scripted action ids (added after the results, to measure how often a share-based change falls on a
    scripted action); salt 0 is the declared run."""
    w = ScriptWorld()
    T = release_day * DAY + 10 * 3600
    out = []
    aid = [10 ** 9 + 100000 * salt]

    def a(uid, kind, t, attrs):
        aid[0] += 1
        if kind == "session":
            w.sessions.setdefault(uid, []).append(t)
        return (aid[0], uid, kind, t, attrs)

    def s1(platform, method, retried=False, tag="S1"):
        u = w.add_user(platform, release_day)
        w.signup_t[u], w.method[u] = T + 40, method
        acts = [a(u, "session", T, (platform, None)), a(u, "paywall", T + 10, ("onboarding", True)),
                a(u, "signup", T + 40, (method,)), a(u, "wstart", T + 100, (f"ws{u}", "strength", False, None)),
                a(u, "wdone", T + 1300, (f"ws{u}", 1200, False, None)), a(u, "paywall", T + 1500, ("home", False)),
                a(u, "purchase", T + 1530, ("monthly", 12.99, retried, T + 1530, f"ts{u}"))]
        out.append((f"{tag} {platform} {method}", acts))

    def s2(platform):
        u = w.add_user(platform, release_day - 30)
        w.signup_t[u], w.method[u] = T - 5 * DAY, "email"
        acts = [a(u, "session", T, (platform, T + 300)), a(u, "wstart", T + 60, (f"ws{u}", "cardio", False, None)),
                a(u, "wdone", T + 960, (f"ws{u}", 900, False, None))]
        out.append((f"S2 {platform}", acts))

    def s3(platform):
        u = w.add_user(platform, release_day)
        out.append((f"S3 {platform}", [a(u, "session", T, (platform, None)), a(u, "paywall", T + 10, ("onboarding", True))]))

    def s5(platform):
        u = w.add_user(platform, release_day - 30)
        w.signup_t[u], w.method[u] = T - 5 * DAY, "email"
        acts = [a(u, "session", T, (platform, None)),
                a(u, "wstart", T + 60, (f"wo{u}", "yoga", True, T + 60 + 900 + 3 * 3600)),
                a(u, "wdone", T + 960, (f"wo{u}", 900, True, T + 60 + 900 + 3 * 3600))]
        out.append((f"S5 {platform} offline", acts))

    if not extended:
        s1("ios", "email")
        s2("ios")
        s3("android")
    else:
        for p in ("ios", "android"):
            for m in ("email", "apple", "google"):
                s1(p, m)
            s2(p)
            s3(p)
            s1(p, "email", retried=True, tag="S4 retry")
            s5(p)
    return w, out


def contract(spec, release_day, extended=False, salt=0):
    """Run the contract on a build or server change. Returns (caught, reasons). Remote settings are never tested."""
    ch = Change(spec, release_day)
    if ch.channel == "remote_setting":
        return False, ["not tested: a remote setting ships without a release"]
    plan = apply_plan_ops(base_plan(), ch.plan_ops)
    added = {o["event"] for o in ch.plan_ops if o["op"] == "plan_add_event"}
    w, runs = scripts(release_day, extended, salt)
    clean = Emitter(w, None, mode="test", staging=True)
    test = Emitter(w, ch, mode="test", staging=True)
    reasons = []
    for name, acts in runs:
        exp = Counter()
        for x in acts:
            seen = set()
            for e in clean.emit(x):
                if e[0] not in seen:
                    seen.add(e[0])
                    exp[e[1]] += 1
        got, seen = Counter(), set()
        landed = []
        for x in acts:
            for e in test.emit(x):
                if e[0] in seen:
                    continue
                seen.add(e[0])
                landed.append(e)
                got[e[1]] += 1
        for n in added:
            got.pop(n, None)
        if got != exp:
            reasons.append(f"{name}: events {dict(got)} not {dict(exp)}")
        for e in landed:
            v = violations(plan, e[1], e[7], strict=True)
            if v:
                reasons.append(f"{name}: {e[1]} schema {v}")
            uid = e[9]
            st = w.signup_t.get(uid)
            signed = st is not None and e[8] >= st
            if e[1] == "signup_completed":
                if e[2] != f"a{uid}" or e[3] != f"u{uid}":
                    reasons.append(f"{name}: signup ids do not link the device")
            elif signed:
                if e[3] != f"u{uid}":
                    reasons.append(f"{name}: {e[1]} user id {e[3]}")
            else:
                if e[3] is not None or (e[6] == "client" and e[2] != f"a{uid}"):
                    reasons.append(f"{name}: {e[1]} pre-signup ids")
            if abs(e[4] - e[8]) > 5:
                reasons.append(f"{name}: {e[1]} event time off by {round(e[4] - e[8])} s")
    screens = set(base_plan()["screens"]) | set(ch.screens)
    missing = screens - set(plan["screens"])
    if missing:
        reasons.append(f"screens without a plan entry: {sorted(missing)}")
    return bool(reasons), reasons


# ---------- landed monitors ----------

def _mean_sd(xs):
    xs = [x for x in xs if x is not None]
    if len(xs) < 7:
        return None, None
    m = sum(xs) / len(xs)
    sd = math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))
    return m, sd


def alarms(series, d_start, d_end, plan_for_day, p=None, arms=("dash", "mon", "sem")):
    """Run the daily checks for data days d_start <= d < d_end. Returns {arm: [(found_day, check, element, data_day)]}.
    series: {day: aggregate} covering at least the trailing window before d_start."""
    p = {**DEFAULTS, **(p or {})}
    out = {a: [] for a in arms}
    T = p["trail"]
    for d in range(d_start, d_end):
        s = series[d]
        plan = plan_for_day(d)
        if "mon" in arms:
            for n in plan["events"]:
                c = s["count"].get(n, 0)
                prev = [series[d - 7 * k]["count"].get(n, 0) for k in (1, 2, 3, 4) if (d - 7 * k) in series]
                if len(prev) == 4:
                    mu = sum(prev) / 4
                    if mu >= p["vol_min"] and (c < p["vol_lo"] * mu or c > p["vol_hi"] * mu):
                        out["mon"].append((d + 1, "volume", n, d))
                f = s["fail"].get(n, 0)
                if c and f >= p["fail_min"] and f / c > p["fail_share"]:
                    out["mon"].append((d + 1, "schema", n, d))
            for n, c in s["unplanned"].items():
                if c >= p["unplanned_min"]:
                    out["mon"].append((d + 1, "schema", n, d))
        for m in METRICS:
            x = s["metrics"][m]
            if x is None:
                continue
            hist = [series[d - k]["metrics"][m] for k in range(1, T + 1) if (d - k) in series]
            mu, sd = _mean_sd(hist)
            if mu is None:
                continue
            found = d + READ_LAG[m]
            if "mon" in arms and sd > 0 and abs(x - mu) > p["metric_k"] * sd:
                out["mon"].append((found, "metric", m, d))
            if "dash" in arms and mu != 0 and abs(x / mu - 1) > p["dash"]:
                out["dash"].append((found, "dashboard", m, d))
        if "sem" in arms:
            if s["txn_dup_n"] >= p["txn_min"] and s["txn_dup"] > p["txn_share"]:
                out["sem"].append((d + 1, "transaction id", "purchase_completed", d))
            for ev in LINK_EVENTS:
                x = s["link"].get(ev)
                if x is None:
                    continue
                hist = [series[d - k]["link"].get(ev) for k in range(1, T + 1) if (d - k) in series]
                hist = [h for h in hist if h is not None]
                if len(hist) >= 7 and x < sum(hist) / len(hist) - p["link_drop"]:
                    out["sem"].append((d + 1, "identity link", ev, d))
            for n in plan["events"]:
                x = s["fast"].get(n)
                if x is None:
                    continue
                hist = [series[d - k]["fast"].get(n) for k in range(1, T + 1) if (d - k) in series]
                hist = [h for h in hist if h is not None]
                if len(hist) >= 7 and x > sum(hist) / len(hist) + p["fast_rise"]:
                    out["sem"].append((d + 1, "arrival time", n, d))
    return out
