#!/usr/bin/env python3
"""Lint ad platform names against a naming rules file.

Checks Google Ads, Meta and LinkedIn names (or any platform.level defined in
the rules) for token order, fixed vocabularies, retired values, patterns,
characters, case, length, duplicates, the launch month and ID format.

Usage:
  python3 lint_names.py --rules naming-rules.yaml --names names.csv [--out report.csv]
  python3 lint_names.py --rules naming-rules.yaml --registry registry.csv [--out report.csv]
  Add --vocab naming-vocab.csv to override the rules file's vocab_file.

Names CSV, header row required:
  platform, level, name             required, for example: google_ads, campaign, <name>
  account_id, object_id, parent_id  optional; duplicate checks, exemptions, ID format
  status                            optional; removed, deleted, archived,
                                    pending_deletion, canceled, cancelled and
                                    completed rows skip duplicate checks
  start_date                        optional YYYY-MM-DD; compared with the launch
                                    token and with retired_on of retired values
  spend                             optional number in one currency; the summary
                                    then gives the share of spend on failing names
Any other column (expect, notes) is ignored.

Registry mode reads the campaign registry instead. It skips closed rows (with
effective_to) and rows whose platform.level has no rules (owned channels),
builds each name from the token columns, fails rows whose name differs from
that generated name, and lints the result like a names file.

Vocabulary: a CSV with token, value, status (approved or retired), alias_of
and retired_on. A retired value fails on a name with no start_date or one
starting on or after retired_on, and warns on an older name.

Report CSV: one row per finding, or one pass or exempt row per clean name.
Summary lines go to stderr. Exit code 0 when no row failed, 1 when any row
failed, 2 when the rules, vocabulary or input file could not be read.

Standard library only, Python 3.8 or later. The rules file uses the small
YAML subset described at the top of assets/naming-rules.yaml.
"""

import argparse
import csv
import difflib
import os
import re
import sys
from collections import defaultdict

SKIP_DUPLICATE_STATUSES = {"removed", "deleted", "archived", "pending_deletion",
                           "canceled", "cancelled", "completed"}
REPORT_FIELDS = ["row", "platform", "level", "account_id", "object_id", "name",
                 "result", "code", "detail", "suggestion"]
ID_COLUMNS = ("account_id", "object_id", "parent_id")
DATE_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2}")
DIGITS = re.compile(r"^[0-9]+$")
SPREADSHEET_NUMBER = re.compile(r"^[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?$")
UI_ID_FORM = re.compile(r"^([0-9]{3}-[0-9]{3}-[0-9]{4}|act_[0-9]+|urn:li:[A-Za-z]+:[0-9]+)$")


class RulesError(Exception):
    """The rules or vocabulary file is missing, malformed or inconsistent."""


def _cell(row, column):
    return (row.get(column) or "").strip()


# ---------------------------------------------------------------------------
# Rules file reader: a small YAML subset, so the script needs no packages.
# ---------------------------------------------------------------------------

def _strip_comment(line):
    """Drop a # comment that starts the line or follows whitespace, outside quotes."""
    out = []
    quote = None
    prev = " "
    for ch in line:
        if quote:
            if ch == quote:
                quote = None
        elif ch in ("'", '"'):
            quote = ch
        elif ch == "#" and prev in (" ", "\t"):
            break
        out.append(ch)
        prev = ch
    return "".join(out).rstrip()


def _split_inline(inner, lineno):
    """Split the inside of [a, 'b', c] on commas that are not inside quotes."""
    parts, buf, quote = [], [], None
    for ch in inner:
        if quote:
            buf.append(ch)
            if ch == quote:
                quote = None
        elif ch in ("'", '"'):
            quote = ch
            buf.append(ch)
        elif ch == ",":
            parts.append("".join(buf))
            buf = []
        elif ch in "[]{}":
            raise RulesError("line %d: nested lists or maps are not supported" % lineno)
        else:
            buf.append(ch)
    if quote:
        raise RulesError("line %d: unclosed quote" % lineno)
    parts.append("".join(buf))
    return [p.strip() for p in parts if p.strip()]


def _scalar(text, lineno):
    """Turn one value into a string, a list of strings or None."""
    s = text.strip()
    if s.startswith("["):
        if not s.endswith("]"):
            raise RulesError("line %d: an inline list must open and close on one line" % lineno)
        return [_scalar(part, lineno) for part in _split_inline(s[1:-1], lineno)]
    if len(s) >= 2 and s[0] == s[-1] and s[0] in ("'", '"'):
        body = s[1:-1]
        if s[0] == "'":
            return body.replace("''", "'")
        return body.replace('\\"', '"').replace("\\\\", "\\")
    if s in ("", "~", "null"):
        return None
    return s


def _is_item(content):
    return content == "-" or content.startswith("- ")


def _block(lines, pos, indent):
    """Read a map or a list whose lines all sit at this indent."""
    if _is_item(lines[pos][1]):
        items = []
        while pos < len(lines) and lines[pos][0] == indent and _is_item(lines[pos][1]):
            body, lineno = lines[pos][1][1:].strip(), lines[pos][2]
            if not body or (body[0] not in "'\"[" and (": " in body or body.endswith(":"))):
                raise RulesError("line %d: list items must be plain values" % lineno)
            items.append(_scalar(body, lineno))
            pos += 1
        return items, pos
    mapping = {}
    while pos < len(lines) and lines[pos][0] == indent:
        content, lineno = lines[pos][1], lines[pos][2]
        if _is_item(content):
            raise RulesError("line %d: list item where a key was expected" % lineno)
        key, sep, rest = content.partition(":")
        key = key.strip().strip("'\"")
        if not sep or not key:
            raise RulesError("line %d: expected 'key: value'" % lineno)
        if key in mapping:
            raise RulesError("line %d: duplicate key %s" % (lineno, key))
        rest = rest.strip()
        pos += 1
        if rest:
            mapping[key] = _scalar(rest, lineno)
        elif pos < len(lines) and lines[pos][0] > indent:
            mapping[key], pos = _block(lines, pos, lines[pos][0])
        elif pos < len(lines) and lines[pos][0] == indent and _is_item(lines[pos][1]):
            mapping[key], pos = _block(lines, pos, indent)
        else:
            mapping[key] = None
    return mapping, pos


def parse_rules_text(text):
    lines = []
    for lineno, raw in enumerate(text.splitlines(), start=1):
        if not raw.strip():
            continue
        lead = raw[:len(raw) - len(raw.lstrip())]
        if "\t" in lead:
            raise RulesError("line %d: indent with spaces, not tabs" % lineno)
        content = _strip_comment(raw)
        if not content.strip():
            continue
        lines.append((len(content) - len(content.lstrip(" ")), content.strip(), lineno))
    if not lines:
        raise RulesError("the rules file is empty")
    value, pos = _block(lines, 0, lines[0][0])
    if pos != len(lines):
        raise RulesError("line %d: unexpected indentation" % lines[pos][2])
    return value


# ---------------------------------------------------------------------------
# Rules loading and validation
# ---------------------------------------------------------------------------

def _whole_number(value, label):
    if value in (None, ""):
        return None
    try:
        return int(str(value))
    except ValueError:
        raise RulesError("%s must be a whole number" % label)


def _choice(value, allowed, default, label):
    value = default if value in (None, "") else str(value).strip().lower()
    if value not in allowed:
        raise RulesError("%s must be one of: %s" % (label, ", ".join(allowed)))
    return value


def _section(data, key):
    value = data.get(key) or {}
    if not isinstance(value, dict):
        raise RulesError("%s must be a map" % key)
    return value


def read_csv(path, required, label):
    """Rows of a CSV with lowercased headers; RulesError when it cannot be used."""
    try:
        with open(path, newline="", encoding="utf-8-sig") as fh:
            reader = csv.DictReader(fh)
            if not reader.fieldnames:
                raise RulesError("%s %s has no header row" % (label, path))
            reader.fieldnames = [(f or "").strip().lower() for f in reader.fieldnames]
            missing = [c for c in required if c not in reader.fieldnames]
            if missing:
                raise RulesError("%s %s is missing column(s): %s" % (label, path, ", ".join(missing)))
            return list(reader)
    except (OSError, csv.Error, UnicodeDecodeError) as exc:
        raise RulesError("cannot read %s %s: %s" % (label, path, exc))


def _inline_vocab(section):
    """vocab: lists in the rules file. Every value listed there is approved."""
    vocab = {}
    for token, values in section.items():
        if not isinstance(values, list) or not values:
            raise RulesError("vocab.%s must be a non-empty list" % token)
        clean = [str(v).strip() for v in values if v not in (None, "")]
        if len(set(clean)) != len(clean):
            raise RulesError("vocab.%s lists a value twice" % token)
        vocab[token] = dict((v, {"status": "approved", "alias_of": "", "retired_on": ""})
                            for v in clean)
    return vocab


def _csv_vocab(path):
    """The vocabulary CSV: token, value, status, alias_of, retired_on, ..."""
    vocab = {}
    name = os.path.basename(path)
    for lineno, row in enumerate(read_csv(path, ("token", "value", "status"), "vocabulary file"),
                                 start=2):
        token, value = _cell(row, "token"), _cell(row, "value")
        if not token and not value:
            continue
        where = "%s line %d" % (name, lineno)
        if not token or not value:
            raise RulesError("%s: token and value are both required" % where)
        status = _cell(row, "status").lower()
        if status not in ("approved", "retired"):
            raise RulesError("%s: status must be approved or retired" % where)
        retired_on = _cell(row, "retired_on")
        if status == "retired" and not re.match(r"^\d{4}-\d{2}-\d{2}$", retired_on):
            raise RulesError("%s: a retired value needs retired_on as YYYY-MM-DD" % where)
        entries = vocab.setdefault(token, {})
        if value in entries:
            raise RulesError("%s: %s value %s is listed twice" % (where, token, value))
        entries[value] = {"status": status, "alias_of": _cell(row, "alias_of"),
                          "retired_on": retired_on}
    return vocab


def _check_vocab(vocab, delimiter, bad_char, lowercase):
    for token, entries in vocab.items():
        if not any(e["status"] == "approved" for e in entries.values()):
            raise RulesError("vocab %s has no approved value" % token)
        for value, entry in entries.items():
            if delimiter in value:
                raise RulesError("vocab %s value %s contains the delimiter %s; join words with -"
                                 % (token, value, delimiter))
            if (bad_char is not None and bad_char.search(value)) or (lowercase and value != value.lower()):
                raise RulesError("vocab %s value %s uses characters names may not contain"
                                 % (token, value))
            alias = entry["alias_of"]
            if alias and entry["status"] != "retired":
                raise RulesError("vocab %s value %s: alias_of is only for retired values" % (token, value))
            if alias and entries.get(alias, {}).get("status") != "approved":
                raise RulesError("vocab %s value %s: alias_of %s is not an approved %s value"
                                 % (token, value, alias, token))


def load_rules(path, vocab_path=None):
    try:
        with open(path, encoding="utf-8-sig") as fh:
            data = parse_rules_text(fh.read())
    except OSError as exc:
        raise RulesError("cannot read %s: %s" % (path, exc))
    if not isinstance(data, dict):
        raise RulesError("the rules file must be a map of keys at the top level")

    delimiter = data.get("delimiter")
    if not isinstance(delimiter, str) or not delimiter:
        raise RulesError("delimiter is required, for example '_'")

    bad_char = None
    allowed = data.get("allowed_characters")
    if allowed:
        try:
            bad_char = re.compile("[^%s]" % allowed)
        except re.error as exc:
            raise RulesError("allowed_characters is not a valid character set: %s" % exc)
    lowercase = str(data.get("lowercase") or "yes").strip().lower() in ("yes", "true")

    vocab_file = data.get("vocab_file")
    if vocab_path:
        vocab = _csv_vocab(vocab_path)
    elif vocab_file and data.get("vocab"):
        raise RulesError("define the vocabulary in vocab or in vocab_file, not both")
    elif vocab_file:
        if not isinstance(vocab_file, str):
            raise RulesError("vocab_file must be a path")
        vocab = _csv_vocab(os.path.join(os.path.dirname(os.path.abspath(path)), vocab_file))
    else:
        vocab = _inline_vocab(_section(data, "vocab"))
    _check_vocab(vocab, delimiter, bad_char, lowercase)

    patterns = {}
    for token, pattern in _section(data, "patterns").items():
        if not isinstance(pattern, str):
            raise RulesError("patterns.%s must be a quoted regular expression" % token)
        if token in vocab:
            raise RulesError("%s is defined in both vocab and patterns" % token)
        try:
            patterns[token] = re.compile(pattern)
        except re.error as exc:
            raise RulesError("patterns.%s is not a valid regular expression: %s" % (token, exc))

    levels = {}
    raw_levels = _section(data, "levels")
    if not raw_levels:
        raise RulesError("levels must define at least one platform.level")
    for key, cfg in raw_levels.items():
        label = "levels." + key
        if key.count(".") != 1:
            raise RulesError("%s: name levels as platform.level, for example meta.ad_set" % label)
        if not isinstance(cfg, dict):
            raise RulesError("%s must be a map" % label)
        tokens = cfg.get("tokens")
        if not isinstance(tokens, list) or not tokens:
            raise RulesError("%s.tokens must be a non-empty list" % label)
        for token in tokens:
            if token not in vocab and token not in patterns:
                raise RulesError("%s uses token %s, which has no vocab list or pattern" % (label, token))
        min_tokens = _whole_number(cfg.get("min_tokens"), label + ".min_tokens")
        if min_tokens is None:
            min_tokens = len(tokens)
        if not 1 <= min_tokens <= len(tokens):
            raise RulesError("%s.min_tokens must be between 1 and the number of tokens" % label)
        levels[key.lower()] = {
            "tokens": tokens,
            "min_tokens": min_tokens,
            "max_length": _whole_number(cfg.get("max_length"), label + ".max_length"),
            "platform_max": _whole_number(cfg.get("platform_max"), label + ".platform_max"),
            "platform_unit": _choice(cfg.get("platform_unit"), ("chars", "bytes"), "chars",
                                     label + ".platform_unit"),
            "unique_within": _choice(cfg.get("unique_within"), ("account", "parent", "none"),
                                     "parent", label + ".unique_within"),
            "duplicates": _choice(cfg.get("duplicates"), ("fail", "warn"), "warn",
                                  label + ".duplicates"),
        }

    exempt = data.get("exempt_ids") or []
    if not isinstance(exempt, list):
        raise RulesError("exempt_ids must be a list")
    exempt_any, exempt_scoped = set(), set()
    for item in exempt:
        text = str(item or "").strip()
        if ":" in text:
            platform, _sep, object_id = text.partition(":")
            exempt_scoped.add((platform.strip().lower(), object_id.strip()))
        elif text:
            exempt_any.add(text)
    return {
        "delimiter": delimiter,
        "bad_char": bad_char,
        "lowercase": lowercase,
        "vocab": vocab,
        "approved": dict((t, [v for v, e in entries.items() if e["status"] == "approved"])
                         for t, entries in vocab.items()),
        "patterns": patterns,
        "levels": levels,
        "exempt_any": exempt_any,
        "exempt_scoped": exempt_scoped,
    }


# ---------------------------------------------------------------------------
# Checks
# ---------------------------------------------------------------------------

def _retired(token, value, entry, start_date):
    """Fail a retired value on a new name; warn on a name that started before retirement."""
    alias = entry["alias_of"]
    detail = "%s value '%s' was retired on %s" % (token, value, entry["retired_on"])
    if DATE_PREFIX.match(start_date) and start_date[:10] < entry["retired_on"]:
        parses_as = " as " + alias if alias else ""
        return ("warn", "retired_value", detail + "; legacy name, still parses" + parses_as, alias)
    return ("fail", "retired_value",
            detail + "; names without a start_date or starting since then use the current value", alias)


def lint_name(name, cfg, rules, start_date=""):
    """Findings for one name, as (result, code, detail, suggestion) tuples."""
    if not name.strip():
        return [("fail", "empty_name", "the name is empty", "")]
    findings = []
    work = name.strip()
    if work != name:
        findings.append(("fail", "whitespace", "leading or trailing spaces", work))
    if any(ch.isspace() for ch in work):
        findings.append(("fail", "whitespace", "spaces or tabs inside the name", ""))
    if rules["lowercase"] and work != work.lower():
        findings.append(("fail", "case", "capital letters", work.lower()))
    text = work.lower() if rules["lowercase"] else work
    if rules["bad_char"] is not None:
        bad = sorted(set(ch for ch in rules["bad_char"].findall(text) if not ch.isspace()))
        if bad:
            findings.append(("fail", "charset", "characters not allowed: " + " ".join(bad), ""))

    if cfg["max_length"] and len(name) > cfg["max_length"]:
        findings.append(("fail", "too_long", "%d characters, house limit %d"
                         % (len(name), cfg["max_length"]), ""))
    if cfg["platform_max"]:
        unit = cfg["platform_unit"]
        size = len(name.encode("utf-8")) if unit == "bytes" else len(name)
        if size > cfg["platform_max"]:
            findings.append(("fail", "over_platform_limit", "%d %s, platform limit %d %s"
                             % (size, unit, cfg["platform_max"], unit), ""))

    tokens = text.split(rules["delimiter"])
    expected = cfg["tokens"]
    if "" in tokens:
        findings.append(("fail", "empty_token", "doubled, leading or trailing delimiter", ""))
    if not cfg["min_tokens"] <= len(tokens) <= len(expected):
        if cfg["min_tokens"] == len(expected):
            want = str(len(expected))
        else:
            want = "%d to %d" % (cfg["min_tokens"], len(expected))
        findings.append(("fail", "token_count", "%d tokens, expected %s: %s"
                         % (len(tokens), want, rules["delimiter"].join(expected)), ""))
        return findings
    for value, token in zip(tokens, expected):
        if not value:
            continue
        if token in rules["vocab"]:
            entry = rules["vocab"][token].get(value)
            if entry is None:
                close = difflib.get_close_matches(value, rules["approved"][token], n=1, cutoff=0.6)
                findings.append(("fail", "vocab", "%s value '%s' is not in the vocabulary"
                                 % (token, value), close[0] if close else ""))
            elif entry["status"] == "retired":
                findings.append(_retired(token, value, entry, start_date))
        elif not rules["patterns"][token].fullmatch(value):
            findings.append(("fail", "pattern", "%s value '%s' does not match its pattern"
                             % (token, value), ""))
    return findings


def check_launch(name, cfg, start_date, rules):
    """Warn when the launch token disagrees with the start date's year and month."""
    if not start_date or "launch" not in cfg["tokens"]:
        return None
    text = name.strip().lower() if rules["lowercase"] else name.strip()
    tokens = text.split(rules["delimiter"])
    position = cfg["tokens"].index("launch")
    if not cfg["min_tokens"] <= len(tokens) <= len(cfg["tokens"]) or position >= len(tokens):
        return None
    value = tokens[position]
    pattern = rules["patterns"].get("launch")
    if pattern is not None and not pattern.fullmatch(value):
        return None
    match = re.match(r"^(\d{4})-(\d{2})-\d{2}", start_date)
    if not match:
        return ("warn", "start_date_format", "start_date '%s' is not YYYY-MM-DD" % start_date, "")
    expected = match.group(1) + match.group(2)
    if value != expected:
        return ("warn", "launch_mismatch", "launch is %s but start_date is in %s"
                % (value, expected), "")
    return None


def check_ids(row):
    """Warn about IDs that will not join: UI display forms, spreadsheet damage, non-digits."""
    findings = []
    for column in ID_COLUMNS:
        value = _cell(row, column)
        if not value:
            continue
        if DIGITS.match(value):
            if len(value) > 15 and set(value[15:]) == {"0"}:
                findings.append(("warn", "bad_id", "%s %s: every digit after the 15th is 0, the mark "
                                 "of a spreadsheet that rounded it; re-export as text" % (column, value), ""))
        elif SPREADSHEET_NUMBER.match(value):
            findings.append(("warn", "bad_id", "%s %s is in scientific notation or has a decimal "
                             "point; re-export the ID as text" % (column, value), ""))
        elif UI_ID_FORM.match(value):
            findings.append(("warn", "bad_id", "%s %s is a display form; store digits only"
                             % (column, value), re.sub(r"[^0-9]", "", value.split(":")[-1])))
        else:
            findings.append(("warn", "bad_id", "%s %s is not digits only" % (column, value), ""))
    return findings


def _is_exempt(platform, object_id, rules):
    return bool(object_id) and (object_id in rules["exempt_any"]
                                or (platform, object_id) in rules["exempt_scoped"])


def registry_rows(rows, rules):
    """Current registry rows as names rows, plus the number skipped for having no rules.

    The name of each row is compared with the name generated from its token
    columns, joined in the level's token order and lowercased like the sheet
    formula. A row with no name (a responsive search ad) is linted on the
    generated name.
    """
    converted, skipped = [], 0
    delimiter = rules["delimiter"]
    for rownum, row in enumerate(rows, start=2):
        if _cell(row, "effective_to"):
            continue
        cfg = rules["levels"].get(_cell(row, "platform").lower() + "." + _cell(row, "level").lower())
        if cfg is None:
            skipped += 1
            continue
        values = [_cell(row, token) for token in cfg["tokens"]]
        if rules["lowercase"]:
            values = [v.lower() for v in values]
        generated = delimiter.join(v for v in values if v)
        name = (row.get("name") or "").strip()
        extra = []
        if not generated:
            extra.append(("fail", "registry_tokens", "no token columns are filled", ""))
        elif name and (name.lower() if rules["lowercase"] else name) != generated:
            parts = (name.lower() if rules["lowercase"] else name).split(delimiter)
            diffs = ["%s is '%s' in the name and '%s' in its column"
                     % (token, parts[i] if i < len(parts) else "", values[i])
                     for i, token in enumerate(cfg["tokens"])
                     if (parts[i] if i < len(parts) else "") != values[i]]
            extra.append(("fail", "registry_mismatch", "; ".join(diffs) or "token count differs",
                          generated))
        new = dict(row)
        new["name"] = name or generated
        new["_rownum"] = rownum
        new["_extra"] = extra
        converted.append(new)
    return converted, skipped


def lint_rows(rows, rules):
    """Return (base, findings, exempt) per row, with duplicate checks applied."""
    entries = []
    duplicate_groups = defaultdict(list)
    by_id = defaultdict(list)
    for position, row in enumerate(rows, start=2):
        platform = _cell(row, "platform").lower()
        level = _cell(row, "level").lower()
        name = row.get("name") or ""
        base = {"row": row.get("_rownum", position), "platform": platform, "level": level,
                "account_id": _cell(row, "account_id"),
                "object_id": _cell(row, "object_id"), "name": name,
                "spend": _cell(row, "spend")}
        if _is_exempt(platform, base["object_id"], rules):
            entries.append((base, [], True))
            continue
        key = platform + "." + level
        cfg = rules["levels"].get(key)
        if cfg is None:
            entries.append((base, [("fail", "unknown_level", "no rules for %s" % key, "")], False))
            continue
        start_date = _cell(row, "start_date")
        findings = list(row.get("_extra") or []) + lint_name(name, cfg, rules, start_date)
        launch = check_launch(name, cfg, start_date, rules)
        if launch:
            findings.append(launch)
        findings.extend(check_ids(row))
        index = len(entries)
        entries.append((base, findings, False))
        status = _cell(row, "status").lower()
        if name.strip() and cfg["unique_within"] != "none" and status not in SKIP_DUPLICATE_STATUSES:
            scope = base["account_id"] if cfg["unique_within"] == "account" else _cell(row, "parent_id")
            duplicate_groups[(key, scope, name.strip().lower())].append(index)
        if base["object_id"]:
            by_id[(key, base["object_id"])].append(index)

    for (key, _scope, _name), members in duplicate_groups.items():
        object_ids = set(entries[i][0]["object_id"] for i in members)
        if len(members) < 2 or (len(object_ids) == 1 and "" not in object_ids):
            continue
        cfg = rules["levels"][key]
        for i in members:
            others = ", ".join(str(entries[j][0]["row"]) for j in members if j != i)
            entries[i][1].append((cfg["duplicates"], "duplicate_name",
                                  "same name in the same %s as row %s" % (cfg["unique_within"], others), ""))
    for members in by_id.values():
        names = set(entries[i][0]["name"].strip() for i in members)
        if len(names) > 1:
            for i in members:
                entries[i][1].append(("warn", "id_has_several_names",
                                      "object_id appears with %d different names" % len(names), ""))
    return entries


# ---------------------------------------------------------------------------
# Command line
# ---------------------------------------------------------------------------

def spend_summary(entries):
    """Share of spend on failing names per platform, or None when no row has spend."""
    totals, failing = defaultdict(float), defaultdict(float)
    for base, findings, exempt in entries:
        try:
            amount = float(base["spend"].replace(",", ""))
        except ValueError:
            continue
        totals[base["platform"]] += amount
        if not exempt and any(f[0] == "fail" for f in findings):
            failing[base["platform"]] += amount
    if not totals:
        return None
    parts = []
    for platform in sorted(totals):
        share = 100.0 * failing[platform] / totals[platform] if totals[platform] else 0.0
        parts.append("%s %.1f%% of %.2f" % (platform, share, totals[platform]))
    return "spend on failing names: " + ", ".join(parts)


def main(argv=None):
    parser = argparse.ArgumentParser(description="Lint ad platform names against a naming rules file.")
    parser.add_argument("--rules", required=True, help="naming rules YAML file")
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--names", help="CSV of names to check")
    source.add_argument("--registry", help="campaign registry CSV to check against its token columns")
    parser.add_argument("--vocab", help="vocabulary CSV; overrides vocab_file in the rules")
    parser.add_argument("--out", help="write the report to this CSV instead of stdout")
    args = parser.parse_args(argv)

    try:
        rules = load_rules(args.rules, args.vocab)
    except RulesError as exc:
        print("rules error: %s" % exc, file=sys.stderr)
        return 2

    label = "registry" if args.registry else "names"
    try:
        rows = read_csv(args.registry or args.names, ("platform", "level", "name"), label + " file")
    except RulesError as exc:
        print("%s error: %s" % (label, exc), file=sys.stderr)
        return 2
    skipped = 0
    if args.registry:
        rows, skipped = registry_rows(rows, rules)

    entries = lint_rows(rows, rules)
    report = []
    totals = {"pass": 0, "warn": 0, "fail": 0, "exempt": 0}
    for base, findings, exempt in entries:
        if exempt:
            totals["exempt"] += 1
            report.append(dict(base, result="exempt", code="exempt",
                               detail="object_id is in exempt_ids", suggestion=""))
        elif not findings:
            totals["pass"] += 1
            report.append(dict(base, result="pass", code="pass", detail="", suggestion=""))
        else:
            totals["fail" if any(f[0] == "fail" for f in findings) else "warn"] += 1
            for result, code, detail, suggestion in findings:
                report.append(dict(base, result=result, code=code, detail=detail,
                                   suggestion=suggestion))

    try:
        out = open(args.out, "w", newline="", encoding="utf-8") if args.out else sys.stdout
    except OSError as exc:
        print("output error: %s" % exc, file=sys.stderr)
        return 2
    try:
        writer = csv.DictWriter(out, fieldnames=REPORT_FIELDS, lineterminator="\n",
                                extrasaction="ignore")
        writer.writeheader()
        writer.writerows(report)
    finally:
        if args.out:
            out.close()

    summary = "%d %s: %d pass, %d warn, %d fail, %d exempt" % (
        len(entries) + skipped, "current registry rows" if args.registry else "names",
        totals["pass"], totals["warn"], totals["fail"], totals["exempt"])
    if args.registry:
        summary += ", %d skipped (no rules for the level)" % skipped
    print(summary, file=sys.stderr)
    spend = spend_summary(entries)
    if spend:
        print(spend, file=sys.stderr)
    return 1 if totals["fail"] else 0


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