"""The pre-release checks (DESIGN-web.md, arms 3, 5 and 6), read from the journeys of a build's browser run.

plain_check looks only at the data layer, in three sessions, on site builds. full_check looks at the data layer and at what
leaves the browser, in 14 sessions, on site builds and tag publishes. The morning replay is full_check on any channel.
Every assertion here has a planted fault in tests/test_web_checks.py that must make it fail.
"""
from collections import Counter

from .measure import LEAD_EVENTS, MEASURED

HIT_EVENTS = ("page_view", "cta_click", "plan_selected", "form_start", "form_error", "demo_request", "asset_download")
ATTR = {
    "paid": {"channel": "paid", "campaign_source": "linkedin", "campaign_medium": "paid_social", "campaign_name": "spring_demo"},
    "email": {"channel": "email", "campaign_source": "newsletter", "campaign_medium": "email", "campaign_name": "monthly_digest"},
    "organic": {"channel": "organic", "campaign_source": None, "campaign_medium": None, "campaign_name": None},
    "direct": {"channel": "direct", "campaign_source": None, "campaign_medium": None, "campaign_name": None},
}


def expected_events(actions):
    """What a session's actions call for, from the taxonomy's "when it fires" column."""
    c = Counter()
    for a in actions:
        kind = a[0]
        if kind == "page":
            c["page_view"] += 1
        elif kind == "plan":
            c["plan_selected"] += 1
        elif kind == "cta":
            c["cta_click"] += 1
        elif kind == "form_focus":
            c["form_start"] += 1
        elif kind == "form_invalid":
            c["form_error"] += 1
        elif kind == "submit":
            c["demo_request" if a[1] == "demo" else "asset_download"] += 1
    return c


def check_pushes(rec, spec):
    """The data layer of one session: it completes, every push passes the strict schema, and the counts are as called for."""
    out = []
    if rec.get("stopped"):
        out.append(f"session stopped: {rec['stopped'][:70]}")
    if rec.get("errors"):
        out.append(f"page error: {rec['errors'][0][:70]}")
    pushes = [p for p in rec["pushes"] if isinstance(p, dict)]
    for p in pushes:
        v = spec.violations(p.get("event"), p, "dl", True)
        if v:
            out.append(f"data layer {p.get('event')}: {v[0][:70]}")
    got = Counter(p.get("event") for p in pushes)
    exp = expected_events(rec["actions"])
    for e in HIT_EVENTS:
        if got[e] != exp[e]:
            out.append(f"data layer {e}: {got[e]} pushes, expected {exp[e]}")
    return out


def check_hits(rec, spec, prices):
    """What left the browser in one session."""
    entry, consent = rec["tuple"].split(".")[:2]
    hits = [h for h in rec["hits"] if isinstance(h, dict)]
    out = []
    if consent not in MEASURED:
        if hits:
            out.append(f"{len(hits)} hits with no consent")
        return out
    if rec.get("hits_before_decision"):
        out.append(f"{rec['hits_before_decision']} hits before the consent decision")
    for h in hits:
        v = spec.violations(h.get("event"), h, "hit", True)
        if v:
            out.append(f"hit {h.get('event')}: {v[0][:70]}")
    pushes = [p for p in rec["pushes"] if isinstance(p, dict) and p.get("event") in HIT_EVENTS]
    ids = Counter(h.get("event_id") for h in hits)
    want = {p.get("event_id") for p in pushes}
    for p in pushes:
        n = ids[p.get("event_id")]
        if n != 1:
            out.append(f"{p.get('event')}: {n} hits for one event")
    for k in ids:
        if k not in want:
            out.append("a hit with no matching data layer event")
    if len({h.get("visitor_id") for h in hits}) > 1:
        out.append("more than one visitor id in a session")
    if len({h.get("session_id") for h in hits}) > 1:
        out.append("more than one session id in a session")
    attr = ATTR[entry]
    for h in hits:
        if h.get("event") == "page_view" or h.get("event") in LEAD_EVENTS:
            for k, v in attr.items():
                if h.get(k) != v:
                    out.append(f"hit {h.get('event')}: {k} is {h.get(k)!r}, expected {v!r}")
    plan = next((a for a in rec["actions"] if a[0] == "plan"), None)
    for h in hits:
        if h.get("event") == "demo_request":
            want_plan = plan[1] if plan else "undecided"
            want_value = prices[(plan[1], plan[2])] if plan else 0
            if h.get("plan_id") != want_plan:
                out.append(f"hit demo_request: plan {h.get('plan_id')!r}, the visitor chose {want_plan!r}")
            if h.get("annual_value") != want_value:
                out.append(f"hit demo_request: annual value {h.get('annual_value')!r}, the visitor's plan costs {want_value}")
    return out


def _dedupe(rows):
    seen, out = set(), []
    for r in rows:
        if r not in seen:
            seen.add(r)
            out.append(r)
    return out


def plain_check(journeys, spec, sessions):
    reasons = []
    for s in sessions:
        reasons += check_pushes(journeys[s], spec)
    return _dedupe(reasons)


def full_check(journeys, spec, sessions, prices):
    reasons = []
    for s in sessions:
        reasons += check_pushes(journeys[s], spec)
        reasons += check_hits(journeys[s], spec, prices)
    return _dedupe(reasons)
