#!/usr/bin/env python3
"""Lint event names, property names or destination mappings.

Implements the rules in references/linter-rules.md. Standard library only.
Reads a file (or stdin when the path is "-"), prints one finding per line
and exits 1 when any error is found. It never changes anything.

  python3 lint_event_names.py events.txt
  python3 lint_event_names.py events.txt --objects objects.txt --actions actions.txt
  python3 lint_event_names.py properties.txt --kind property
  python3 lint_event_names.py user_properties.txt --kind user_property
  python3 lint_event_names.py mapping.csv --kind mapping
  python3 lint_event_names.py events.txt --convention title_case

Input formats
  event, user_property: one raw name per line. Blank lines and lines that
    start with # are skipped. Paste names exactly as observed.
  property: one name per line, optionally "name,type".
  mapping: CSV with the header canonical_name,destination,destination_name
    and optional columns canonical_property,destination_property (one row
    per parameter sent to a destination). Other columns, such as a GTM
    datalayer_event, are ignored.
  vocabulary files: one term per line; # starts a comment. An optional line
    "forbidden: removed=deleted, cancelled=canceled, clicked" lists
    synonyms that must not be used, with the approved term after "=".

--convention (event names only): snake_case (default), title_case or
camel_case. For a kept title_case or camel_case taxonomy, names that do not
follow it are the error, and GA4 syntax, length, reserved-name and prefix
checks move to the ga4 rows of a mapping.

The reserved lists were copied from the vendors' live docs on 2026-10-17.
Refresh them from the URLs in sources.yaml before relying on them.
"""
import argparse
import csv
import re
import sys
from collections import defaultdict

GA4_EVENT_MAX = 40
HOUSE_EVENT_WARN = 32
GA4_PARAM_MAX = 40
GA4_USER_PROPERTY_MAX = 24
MAX_TOKENS = 5
GA4_PARAMS_PER_EVENT = 25

SNAKE = re.compile(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*")
TITLE_WORD = r"(?:[A-Z][a-z0-9]*|[A-Z0-9]{2,})"
CONVENTIONS = {
    "snake_case": SNAKE,
    "title_case": re.compile(TITLE_WORD + r"(?: " + TITLE_WORD + r")*"),
    "camel_case": re.compile(r"[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*"),
}

GA4_RESERVED_EVENTS = {
    # web streams
    "ad_impression", "app_remove", "app_store_refund",
    "app_store_subscription_cancel", "app_store_subscription_renew", "click",
    "error", "file_download", "first_open", "first_visit", "form_start",
    "form_submit", "in_app_purchase", "page_view", "scroll", "session_start",
    "user_engagement", "view_complete", "video_complete", "video_progress",
    "video_start", "view_search_results",
    # app streams
    "ad_activeview", "ad_click", "ad_exposure", "ad_query", "ad_reward",
    "adunit_exposure", "app_clear_data", "app_exception", "app_install",
    "app_update", "app_upgrade", "dynamic_link_app_open",
    "dynamic_link_app_update", "dynamic_link_first_open", "firebase_campaign",
    "firebase_in_app_message_action", "firebase_in_app_message_dismiss",
    "firebase_in_app_message_impression", "notification_dismiss",
    "notification_foreground", "notification_open", "notification_receive",
    "notification_send", "os_update",
    # app streams, from the Firebase Analytics Event reference
    "app_background", "app_store_subscription_convert",
    "session_start_with_rollout",
    # house rule: not on Google's reserved lists, but the Measurement Protocol
    # reference allows it only for app streams
    "screen_view",
}

# Google's own events on app streams: the Measurement Protocol allows them only
# for app streams and the Firebase SDK has constants for ad_impression and
# screen_view. ad_impression and in_app_purchase are also reserved on web
# streams; screen_view is not on Google's reserved lists.
GA4_APP_OWN_EVENTS = {"ad_impression", "in_app_purchase", "screen_view"}

# GA4 marks purchase (web and app) and four app-stream events as key events
# by default, and the shopping events when a linked Google Ads account has
# Ads Personalization on (key events help page).
GA4_AUTO_KEY_EVENTS = {
    "purchase",
    "first_open", "in_app_purchase", "app_store_subscription_convert",
    "app_store_subscription_renew",
    "add_to_cart", "add_to_wishlist", "begin_checkout",
    "session_start", "view_item", "view_item_list", "view_search_results",
}

GA4_RECOMMENDED_EVENTS = {
    "login", "search", "select_content", "share", "sign_up",
    "add_payment_info", "add_shipping_info", "add_to_cart", "add_to_wishlist",
    "begin_checkout", "purchase", "refund", "remove_from_cart", "select_item",
    "select_promotion", "view_cart", "view_item", "view_item_list",
    "view_promotion",
    "generate_lead", "qualify_lead", "disqualify_lead", "working_lead",
    "close_convert_lead", "close_unconvert_lead",
    "earn_virtual_currency", "spend_virtual_currency", "join_group",
    "level_start", "level_end", "level_up", "post_score", "tutorial_begin",
    "tutorial_complete", "unlock_achievement",
}

EVENT_RESERVED_PREFIXES = ("firebase_", "google_", "ga_", "query_id")
WEB_ONLY_PREFIXES = ("query_id",)
PARAM_RESERVED_PREFIXES = ("_", "firebase_", "ga_", "google_", "gtag.")

GA4_RESERVED_PARAMS = {
    "cid", "currency", "customer_id", "customerid", "dclid", "gclid",
    "session_id", "sessionid", "sfmc_id", "sid", "srsltid", "uid", "user_id",
    "userid", "firebase_conversion",
}

GA4_RESERVED_USER_PROPERTIES = {
    "cid", "customer_id", "customerid", "first_open_after_install",
    "first_open_time", "first_visit_time",
    "google_allow_ad_personalization_signals", "last_advertising_id_reset",
    "last_deep_link_referrer", "last_gclid", "lifetime_user_engagement",
    "non_personalized_ads", "session_id", "session_number", "sessionid",
    "sfmc_id", "sid", "uid", "user_id", "userid",
}

MIXPANEL_RESERVED_PROPERTIES = {"token", "ip", "distinct_id", "time", "alias"}

PII_EXACT = {
    "email", "email_address", "phone", "phone_number", "first_name",
    "last_name", "full_name", "password", "ip_address", "street_address",
    "date_of_birth", "ssn",
}
PII_TOKENS = {"email", "phone", "password", "passwd", "ssn"}

IRREGULAR_PAST = {
    "sent", "shown", "seen", "begun", "won", "lost", "paid", "set", "built",
    "read", "made", "done", "given", "taken", "written", "chosen", "held",
    "kept", "met", "sold", "bought", "found", "left", "put", "run", "split",
    "shut", "reset", "drawn", "grown", "known", "thrown", "undone",
}
PARTICLES = {"in", "out", "up", "on", "off", "down"}
VALUE_TOKENS = {"test", "tmp", "temp", "new", "old", "final", "copy",
                "legacy", "latest"}
UI_TOKENS = {"click", "clicked", "tap", "tapped", "button", "btn", "link",
             "modal", "hover", "hovered", "icon", "cta"}
FILLER_TOKENS = {"successfully", "success", "event", "action"}
SPELLING_VARIANTS = [
    ("canceled", "cancelled"),
    ("signup", "sign_up"),
    ("login", "log_in"),
    ("logout", "log_out"),
    ("setup", "set_up"),
    ("checkout", "check_out"),
    ("signin", "sign_in"),
]
KNOWN_TYPES = {"string", "number", "integer", "boolean", "timestamp",
               "datetime", "date", "array", "list", "object"}
PROPERTY_HEADERS = {"name,type", "property,type", "property_name,type"}


class Report:
    def __init__(self):
        self.errors = 0
        self.warnings = 0

    def error(self, code, subject, message):
        self.errors += 1
        print("ERROR %s %r: %s" % (code, subject, message))

    def warn(self, code, subject, message):
        self.warnings += 1
        print("WARN  %s %r: %s" % (code, subject, message))


def read_lines(path):
    """Raw lines without the newline; skips blank and # lines."""
    handle = sys.stdin if path == "-" else open(path, encoding="utf-8-sig")
    try:
        lines = []
        for raw in handle:
            line = raw.rstrip("\r\n")
            if not line.strip() or line.lstrip().startswith("#"):
                continue
            lines.append(line)
        return lines
    finally:
        if handle is not sys.stdin:
            handle.close()


def load_vocab(path):
    """Return (terms, forbidden). terms is None when no file is given;
    forbidden maps each forbidden synonym to its approved term ("" if none)."""
    if not path:
        return None, {}
    terms = set()
    forbidden = {}
    with open(path, encoding="utf-8-sig") as handle:
        for raw in handle:
            text = raw.split("#", 1)[0].strip()
            if not text:
                continue
            if text.lower().startswith("forbidden:"):
                for item in text.split(":", 1)[1].split(","):
                    bad, _, good = item.partition("=")
                    if bad.strip():
                        forbidden[bad.strip()] = good.strip()
                continue
            terms.add(text)
    return terms, forbidden


def synonym_message(term, forbidden):
    if forbidden.get(term):
        return "'%s' is a forbidden synonym; use '%s'" % (term, forbidden[term])
    return "'%s' is a forbidden synonym in the vocabulary" % term


def normalise(name):
    """Lowercase, split camelCase, join words with single underscores."""
    text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name.strip())
    text = re.sub(r"[^a-z0-9]+", "_", text.lower())
    return text.strip("_")


def syntax_problems(name):
    if SNAKE.fullmatch(name):
        return []
    found = []
    if any(ord(ch) > 127 for ch in name):
        found.append("non-ASCII character")
    if any(ch.isupper() for ch in name):
        found.append("uppercase letter")
    if " " in name:
        found.append("space")
    for ch, label in (("-", "hyphen"), (".", "dot"), (":", "colon"),
                      ("$", "dollar sign"), ("[", "bracket"), ("/", "slash")):
        if ch in name:
            found.append(label)
    if name[:1].isdigit():
        found.append("starts with a digit")
    if name.startswith("_"):
        found.append("starts with an underscore")
    if "__" in name:
        found.append("double underscore")
    if name.endswith("_"):
        found.append("trailing underscore")
    if not found:
        found.append("character outside a-z, 0-9 and _")
    return found


def looks_past_tense(token):
    return token.endswith("ed") or token in IRREGULAR_PAST


def ga4_syntax_ok(name):
    return (bool(name) and name[0].isalpha()
            and all(ch.isalnum() or ch == "_" for ch in name))


def reserved_message(low):
    if low == "screen_view":
        return ("not on Google's reserved lists, but the Measurement Protocol allows it "
                "only for app streams; Google's own event there, allowed only with its "
                "documented meaning, recorded as an exception")
    if low in GA4_APP_OWN_EVENTS:
        return ("reserved on web streams; Google's own event on app streams, "
                "allowed there only with its documented meaning, recorded as an exception")
    return "GA4 reserved event name"


def prefix_message(low):
    if low.startswith(WEB_ONLY_PREFIXES):
        return "starts with query_id, a reserved prefix on GA4 web streams"
    return "starts with a Firebase and GA4 reserved prefix (firebase_, google_, ga_)"


def lint_event_name(raw, objects, actions, out, convention="snake_case", forbidden=None):
    forbidden = forbidden or {}
    name = raw.strip()
    if not name:
        out.error("N01", raw, "empty name")
        return
    if name != raw:
        out.error("N01", raw, "leading or trailing whitespace")
    low = name.lower()
    snake = convention == "snake_case"
    if snake:
        problems = syntax_problems(name)
        if problems:
            out.error("N03", raw, "not lowercase snake_case: " + ", ".join(problems))
    else:
        problems = [] if CONVENTIONS[convention].fullmatch(name) else [convention]
        if problems:
            out.error("N03", raw, "does not follow the declared %s convention; "
                      "the taxonomy mixes conventions" % convention)
    if name.startswith("$"):
        out.error("N09", raw, "$ names belong to Mixpanel and PostHog default events")
    if low.startswith("[amplitude]"):
        out.error("N09", raw, "[Amplitude] names are reserved for Amplitude internal events")
    if snake:
        if len(name) > GA4_EVENT_MAX:
            out.error("N04", raw, "%d characters; GA4 does not log event names over %d "
                      "and will not report a key event over %d"
                      % (len(name), GA4_EVENT_MAX, GA4_EVENT_MAX))
        elif len(name) > HOUSE_EVENT_WARN:
            out.warn("N05", raw, "%d characters; house margin is %d"
                     % (len(name), HOUSE_EVENT_WARN))
        if low in GA4_RESERVED_EVENTS:
            out.error("N08", raw, reserved_message(low))
        if low.startswith(EVENT_RESERVED_PREFIXES):
            out.error("N09", raw, prefix_message(low))
        if low in GA4_RECOMMENDED_EVENTS:
            out.warn("N10", raw, "GA4 recommended event; keep only if the trigger matches "
                     "Google's meaning and required parameters exist")
            return
    elif len(name) > GA4_EVENT_MAX:
        out.warn("N04", raw, "%d characters; if it reaches GA4, its destination name must be "
                 "%d or fewer (lint the mapping)" % (len(name), GA4_EVENT_MAX))
    if problems:
        # Structure rules wait for a clean name; word rules still run on the
        # normalised words so raw observed names get useful findings.
        tokens = [t for t in normalise(name).split("_") if t]
    else:
        key = name if snake else normalise(name)
        if not snake and key in GA4_RECOMMENDED_EVENTS:
            # Google's recommended names (Login, Sign Up, Purchase) are exempt
            # from the structure rules; M04 judges them on the ga4 rows.
            return
        tokens = key.split("_")
        if len(tokens) < 2:
            out.error("N06", raw, "one token; a name needs an object and an action")
            return
        if len(tokens) == 2 and tokens[-1] in PARTICLES:
            out.error("N06", raw, "a verb and particle only (%s); a name needs an object "
                      "and an action" % key)
            return
        if len(tokens) > MAX_TOKENS:
            out.warn("N07", raw, "%d tokens; a value or UI location probably belongs in a property"
                     % len(tokens))
        if actions is not None:
            if not any(key.endswith("_" + act) for act in actions):
                bad = [t for t in forbidden if key.endswith("_" + t)]
                if bad:
                    out.warn("R05", raw, synonym_message(bad[0], forbidden))
                else:
                    out.warn("N11", raw, "action is not in the action vocabulary")
        else:
            action = tokens[-1]
            if action in PARTICLES:
                action = tokens[-2]
            if not looks_past_tense(action):
                out.warn("N11", raw, "action '%s' does not look past tense" % action)
        if objects is not None:
            if not any(key.startswith(obj + "_") for obj in objects):
                bad = [t for t in forbidden if key.startswith(t + "_")]
                if bad:
                    out.warn("R05", raw, synonym_message(bad[0], forbidden))
                else:
                    out.warn("N12", raw, "object is not in the object vocabulary")
            elif actions is not None and not any(
                    key == obj + "_" + act for obj in objects for act in actions):
                out.warn("N12", raw, "not exactly one vocabulary object plus one vocabulary action")
    digit_tokens = [t for t in tokens if any(ch.isdigit() for ch in t)]
    if digit_tokens:
        out.warn("N13", raw, "token '%s' contains a digit; steps, versions, dates and IDs "
                 "belong in properties" % digit_tokens[0])
    for code, vocab, message in (
            ("N14", VALUE_TOKENS, "temporary or relative word"),
            ("N15", UI_TOKENS, "UI gesture or element; name the business fact"),
            ("N16", FILLER_TOKENS, "filler word")):
        hits = [t for t in tokens if t in vocab]
        if hits:
            out.warn(code, raw, "%s: %s" % (message, ", ".join(hits)))


def check_collisions(names, out):
    groups = defaultdict(list)
    for name in names:
        key = normalise(name)
        if key:
            groups[key].append(name)
    for key, members in groups.items():
        if len(members) > 1:
            out.error("N17", " / ".join(members),
                      "same name after normalising (%s)" % key)
    near = defaultdict(set)
    for key in groups:
        tokens = key.split("_")
        near[("order",) + tuple(sorted(tokens))].add(key)
        singular = tuple(t[:-1] if len(t) > 3 and t.endswith("s") else t
                         for t in tokens)
        near[("plural",) + singular].add(key)
    reported = set()
    for keys in near.values():
        if len(keys) > 1:
            members = tuple(sorted(raw for key in keys for raw in groups[key]))
            if members in reported:
                continue
            reported.add(members)
            out.warn("N18", " / ".join(members),
                     "likely the same event: word order or singular versus plural")


def check_spelling_variants(names, out):
    padded = [(name, "_" + normalise(name) + "_") for name in names]
    for first, second in SPELLING_VARIANTS:
        with_first = [n for n, p in padded if "_" + first + "_" in p]
        with_second = [n for n, p in padded if "_" + second + "_" in p]
        if with_first and with_second:
            out.warn("N19", ", ".join(with_first + with_second),
                     "mixes '%s' and '%s'; keep one spelling in the vocabulary"
                     % (first, second))


def lint_events(names, objects, actions, out, convention="snake_case", forbidden=None):
    counts = defaultdict(int)
    for name in names:
        counts[name] += 1
    for name, count in counts.items():
        if count > 1:
            out.error("N02", name, "listed %d times" % count)
    unique = list(counts)
    for name in unique:
        lint_event_name(name, objects, actions, out, convention, forbidden)
    check_collisions(unique, out)
    check_spelling_variants(unique, out)
    return len(names)


def lint_property_name(raw, is_user, out, ga4_destination=False):
    """ga4_destination: a parameter name in a ga4 mapping row. Only the GA4,
    personal data and dynamic key rules apply; value and currency are GA4's
    standard parameters and M11 checks that they travel together."""
    name = raw.strip()
    if name != raw:
        out.error("P01", raw, "leading or trailing whitespace")
    if not name:
        out.error("P01", raw, "empty name")
        return
    low = name.lower()
    problems = syntax_problems(name)
    if problems:
        out.error("P01", raw, "not lowercase snake_case: " + ", ".join(problems))
    limit = GA4_USER_PROPERTY_MAX if is_user else GA4_PARAM_MAX
    if len(name) > limit:
        out.error("P02", raw, "%d characters; GA4 limit is %d" % (len(name), limit))
    if low.startswith(PARAM_RESERVED_PREFIXES):
        out.error("P04", raw, "starts with a GA4 reserved prefix")
    if is_user:
        if low in GA4_RESERVED_USER_PROPERTIES:
            out.error("P05", raw, "GA4 reserved user property name")
    elif low == "currency":
        if not ga4_destination:
            out.warn("P03", raw, "reserved for the ISO 4217 code of value or revenue")
    elif low in GA4_RESERVED_PARAMS:
        out.error("P03", raw, "GA4 reserved parameter name")
    if not ga4_destination:
        if low == "bucket":
            out.error("P06", raw, "Mixpanel says never to name a property bucket")
        elif low in MIXPANEL_RESERVED_PROPERTIES:
            out.warn("P06", raw, "Mixpanel reserved property; use only with Mixpanel's meaning")
        if low in ("revenue", "value"):
            out.warn("P07", raw, "Segment reserved property; confirm meaning and units")
    if low in PII_EXACT:
        out.error("P12", raw, "personal data by definition; keep out of analytics properties")
    elif set(low.split("_")) & PII_TOKENS:
        out.warn("P12", raw, "may hold personal data; confirm the value is not an identifier")
    if not problems:
        digit_tokens = [t for t in name.split("_") if any(ch.isdigit() for ch in t)]
        if digit_tokens:
            out.warn("P11", raw, "token '%s' contains a digit; possible dynamic key"
                     % digit_tokens[0])


def lint_properties(lines, is_user, out):
    order = []
    seen = set()
    types = defaultdict(set)
    for line in lines:
        if line.replace(" ", "").lower() in PROPERTY_HEADERS:
            continue
        parts = line.split(",")
        name = parts[0]
        ptype = parts[1].strip().lower() if len(parts) > 1 else ""
        if name not in seen:
            seen.add(name)
            order.append(name)
        if ptype:
            types[name].add(ptype)
    for name in order:
        lint_property_name(name, is_user, out)
        found = types.get(name, set())
        for ptype in sorted(found - KNOWN_TYPES):
            out.warn("P13", name, "unknown type '%s'" % ptype)
        if len(found) > 1:
            out.error("P10", name, "sent with more than one type: " + ", ".join(sorted(found)))
        key = name.strip()
        if "boolean" in found and not key.startswith(("is_", "has_")):
            out.warn("P08", name, "boolean without an is_ or has_ prefix")
        is_time = bool(found & {"timestamp", "datetime"})
        if is_time and not key.endswith("_at"):
            out.warn("P09", name, "timestamp without an _at suffix")
        if found and not is_time and key.endswith("_at"):
            out.warn("P09", name, "ends in _at but is not a timestamp")
        if found:
            if key.endswith("_id") and found != {"string"}:
                out.warn("P15", name, "ends in _id but is not typed string")
            if key.startswith(("is_", "has_")) and found != {"boolean"}:
                out.warn("P15", name, "starts with is_ or has_ but is not typed boolean")
            if key.endswith("_count") and found != {"integer"}:
                out.warn("P15", name, "ends in _count but is not typed integer")
    groups = defaultdict(list)
    for name in order:
        norm = normalise(name)
        if norm:
            groups[norm].append(name)
    for norm, members in groups.items():
        if len(members) > 1:
            out.error("P14", " / ".join(members),
                      "same property after normalising (%s)" % norm)
    return len(order)


def lint_destination_name(dest, dname, canonical, out):
    subject = "%s:%s" % (dest, dname)
    if dest == "ga4":
        if not ga4_syntax_ok(dname):
            out.error("M03", subject, "GA4 needs a letter first, then only letters, numbers and underscores")
        if len(dname) > GA4_EVENT_MAX:
            out.error("M03", subject, "%d characters; GA4 limit is %d" % (len(dname), GA4_EVENT_MAX))
        if dname in GA4_APP_OWN_EVENTS:
            out.error("M03", subject, reserved_message(dname))
        elif dname in GA4_RESERVED_EVENTS:
            out.error("M03", subject, "GA4 reserved name; allowed only for Google's own event "
                      "with its documented meaning, recorded as an exception")
        if dname.lower().startswith(EVENT_RESERVED_PREFIXES):
            out.error("M03", subject, prefix_message(dname.lower()))
        if dname in GA4_RECOMMENDED_EVENTS:
            out.warn("M04", subject, "recommended event; confirm the trigger of '%s' matches "
                     "and required parameters are mapped" % canonical)
        low = dname.lower()
        if dname != low and (low in GA4_RESERVED_EVENTS or low in GA4_RECOMMENDED_EVENTS):
            out.warn("M10", subject, "case variant of Google's '%s'; GA4 event names are case "
                     "sensitive, so this is a separate custom event, not Google's" % low)
        if dname in GA4_AUTO_KEY_EVENTS:
            out.warn("M07", subject, "GA4 can mark this as a key event automatically (purchase "
                     "always; first_open, in_app_purchase and the app store subscription events "
                     "on app streams; the shopping events with a linked Google Ads account and "
                     "Ads Personalization on); record key-event status and the Ads conversion "
                     "it would feed")
    elif dest in ("mixpanel", "posthog"):
        if dname.startswith("$"):
            out.error("M05", subject, "$ names are the vendor's default events")
    elif dest == "amplitude":
        if dname.lower().startswith("[amplitude]") or dname in ("$identify", "$groupidentify"):
            out.error("M05", subject, "reserved Amplitude event name")
    if dname != canonical and not (dest == "ga4" and dname in GA4_RECOMMENDED_EVENTS):
        out.warn("M06", subject, "differs from canonical '%s'; record the reason" % canonical)


def lint_mapping(path, objects, actions, out, convention="snake_case", forbidden=None):
    handle = sys.stdin if path == "-" else open(path, newline="", encoding="utf-8-sig")
    try:
        reader = csv.DictReader(handle)
        needed = {"canonical_name", "destination", "destination_name"}
        fields = {f.strip() for f in (reader.fieldnames or []) if f}
        if not needed.issubset(fields):
            out.error("M00", path, "CSV needs the header canonical_name,destination,destination_name")
            return 0
        rows = []
        for row in reader:
            clean = {}
            for key, value in row.items():
                if key and isinstance(value, str):
                    clean[key.strip()] = value.strip()
            if clean.get("canonical_name") or clean.get("destination_name"):
                rows.append(clean)
    finally:
        if handle is not sys.stdin:
            handle.close()

    canonicals = []
    for row in rows:
        name = row.get("canonical_name", "")
        if name and name not in canonicals:
            canonicals.append(name)
    lint_events(canonicals, objects, actions, out, convention, forbidden)

    by_dest = defaultdict(lambda: defaultdict(set))
    per_canonical = defaultdict(set)
    params = defaultdict(set)
    linted_rows = set()
    linted_params = set()
    for row in rows:
        canonical = row.get("canonical_name", "")
        dest = row.get("destination", "").lower()
        dname = row.get("destination_name", "")
        if not canonical or not dest or not dname:
            out.error("M00", canonical or dname, "row needs canonical_name, destination and destination_name")
            continue
        by_dest[dest][dname].add(canonical)
        per_canonical[(canonical, dest)].add(dname)
        if (dest, dname, canonical) not in linted_rows:
            linted_rows.add((dest, dname, canonical))
            lint_destination_name(dest, dname, canonical, out)
        dprop = row.get("destination_property", "")
        if dprop:
            params[(dest, dname)].add(dprop)
            if dest == "ga4" and dprop not in linted_params:
                linted_params.add(dprop)
                lint_property_name(dprop, False, out, ga4_destination=True)
    for (dest, dname), names in params.items():
        if dest != "ga4":
            continue
        if len(names) > GA4_PARAMS_PER_EVENT:
            out.error("M09", "%s:%s" % (dest, dname), "%d parameters; GA4 logs at most %d per event"
                      % (len(names), GA4_PARAMS_PER_EVENT))
        if "value" in names and "currency" not in names:
            out.error("M11", "%s:%s" % (dest, dname), "value is mapped without currency; GA4 "
                      "needs an ISO 4217 currency whenever value is set")
    for (canonical, dest), dnames in per_canonical.items():
        if len(dnames) > 1:
            out.error("M08", canonical, "sends %d names to %s: %s"
                      % (len(dnames), dest, ", ".join(sorted(dnames))))
    for dest, names in by_dest.items():
        for dname, sources in names.items():
            if len(sources) > 1:
                out.error("M01", "%s:%s" % (dest, dname),
                          "receives %d canonical events: %s; needs equivalent triggers "
                          "and a written dedupe rule" % (len(sources), ", ".join(sorted(sources))))
        groups = defaultdict(set)
        for dname in names:
            groups[normalise(dname)].add(dname)
        for members in groups.values():
            if len(members) > 1:
                out.warn("M02", "%s:%s" % (dest, " / ".join(sorted(members))),
                         "differ only by case or separators")
    return len(rows)


def main(argv=None):
    parser = argparse.ArgumentParser(description="Lint names against the event naming rules.")
    parser.add_argument("path", help="input file, or - for stdin")
    parser.add_argument("--kind", default="event",
                        choices=["event", "property", "user_property", "mapping"])
    parser.add_argument("--objects", help="file with one approved object per line")
    parser.add_argument("--actions", help="file with one approved action per line")
    parser.add_argument("--convention", default="snake_case", choices=sorted(CONVENTIONS),
                        help="declared event name convention (default snake_case)")
    args = parser.parse_args(argv)
    objects, forbidden = load_vocab(args.objects)
    actions, forbidden_actions = load_vocab(args.actions)
    forbidden.update(forbidden_actions)
    out = Report()
    if args.convention != "snake_case":
        print("NOTE convention %s: GA4 syntax, length, reserved-name and prefix checks "
              "apply to ga4 rows of a mapping (--kind mapping)" % args.convention)
    if args.kind == "event":
        checked = lint_events(read_lines(args.path), objects, actions, out, args.convention,
                              forbidden)
    elif args.kind in ("property", "user_property"):
        checked = lint_properties(read_lines(args.path), args.kind == "user_property", out)
    else:
        checked = lint_mapping(args.path, objects, actions, out, args.convention, forbidden)
    print("\n%d checked, %d errors, %d warnings" % (checked, out.errors, out.warnings))
    return 1 if out.errors else 0


if __name__ == "__main__":
    sys.exit(main())
