#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""rule: check a text against one writing rule, chosen by the date or by name."""

import os
import re
import sys
import textwrap
import unicodedata
from collections import namedtuple
from datetime import date
from itertools import pairwise

REVISION = 1
EPOCH = date(1970, 1, 1)
BRICK, RESET = "\x1b[38;2;236;94;82m", "\x1b[0m"

Word = namedtuple("Word", "line col text letters key fold")
Number = namedtuple("Number", "line col text")
Break = namedtuple("Break", "line col length word message")
Rule = namedtuple("Rule", "id name grade desc definition lineage sentences check")
Model = namedtuple("Model", "lines words numbers sentences")


class Fail(Exception):
    """A message for stderr and exit status 2."""


# Tokenizer

def cat(c):
    return unicodedata.category(c)


FOLD_EXTRA = str.maketrans({"æ": "ae", "œ": "oe", "ø": "o", "đ": "d", "ł": "l", "ı": "i"})


def fold(s):
    """Casefold, decompose, drop marks, map the letters that do not decompose. ß goes to ss in casefold."""
    s = unicodedata.normalize("NFD", s.casefold())
    return "".join(c for c in s if cat(c)[0] != "M").translate(FOLD_EXTRA)


def scan(line, ln):
    """Yield the words and numbers of one line, in order."""
    i, n = 0, len(line)
    while i < n:
        c = cat(line[i])
        if c[0] in "LM":
            j = i + 1
            while j < n and (cat(line[j])[0] in "LM" or (
                    line[j] in "'’" and j + 1 < n and cat(line[j - 1])[0] == "L" and cat(line[j + 1])[0] == "L")):
                j += 1
            t = line[i:j]
            yield Word(ln, i + 1, t, sum(cat(x)[0] == "L" for x in t), t.casefold().replace("’", "'"), fold(t))
        elif c == "Nd":
            j = i + 1
            while j < n and (cat(line[j]) == "Nd" or (
                    line[j] in ".," and j + 1 < n and cat(line[j - 1]) == "Nd" and cat(line[j + 1]) == "Nd")):
                j += 1
            yield Number(ln, i + 1, line[i:j])
        else:
            j = i + 1
        i = j


TERMINALS, CLOSERS, OPENERS = ".!?…。！？", "\"')]”’»", "([{\"'`“‘«"
ABBREVIATIONS = {"mr", "mrs", "ms", "dr", "prof", "st", "vs", "cf", "e.g", "i.e"}


def sentence_ends(line):
    """0-based columns of the terminal runs on this line that end a sentence."""
    ends, i, n = [], 0, len(line)
    while i < n:
        if line[i] not in TERMINALS:
            i += 1
            continue
        j = i
        while j < n and line[j] in TERMINALS:
            j += 1
        k = j
        while k < n and line[k] in CLOSERS:
            k += 1
        if k == n or line[k].isspace():
            s = i
            while s and not line[s - 1].isspace():
                s -= 1
            chunk = line[s:i].lstrip(OPENERS).casefold()
            abbreviation = chunk in ABBREVIATIONS or (len(chunk) == 1 and cat(chunk)[0] == "L")
            if not (line[i:j] == "." and abbreviation):
                ends.append(i)
        i = k
    return ends


def model(text):
    if text.startswith("\ufeff"):
        text = text[1:]
    lines = [unicodedata.normalize("NFC", raw.removesuffix("\r")) for raw in text.split("\n")]
    words, numbers, sentences, current = [], [], [], []
    for ln, line in enumerate(lines, 1):
        if not line.strip():
            sentences.append(current)
            current = []
            continue
        events = [(t.col - 1, t) for t in scan(line, ln)] + [(e, None) for e in sentence_ends(line)]
        for _, t in sorted(events, key=lambda e: e[0]):
            if t is None:
                sentences.append(current)
                current = []
            elif isinstance(t, Word):
                words.append(t)
                current.append(t)
            else:
                numbers.append(t)
    sentences.append(current)
    return Model(lines, words, numbers, [s for s in sentences if s])


# The rules: each takes a Model and returns a list of Breaks.

def plural(n, noun):
    return f"{n} {noun}" if n == 1 else f"{n} {noun}s"


def forbidden(m, pred):
    return [Break(w.line, w.col, len(w.text), w.text, f'"{w.text}" is not permitted') for w in m.words if pred(w)]


def marks(m, pattern):
    return [Break(ln, r.start() + 1, len(r.group()), r.group(), f'"{r.group()}" is not permitted')
            for ln, line in enumerate(m.lines, 1) for r in re.finditer(pattern, line)]


def letter_rule(x):
    def check(m):
        out = []
        for w in m.words:
            hit = next((i for i, c in enumerate(w.text) if x in fold(c)), None)
            if hit is not None:
                out.append(Break(w.line, w.col + hit, 1, w.text, f'"{w.text}" contains "{x}"'))
        return out
    return check


def no_dash(m):
    out = []
    for ln, line in enumerate(m.lines, 1):
        for r in re.finditer("[-\u2013\u2014\u2015\u2e3a\u2e3b]+", line):
            run, s, e = r.group(), r.start(), r.end()
            before, after = line[s - 1:s], line[e:e + 1]
            if run.strip("-"):
                bad = True
            elif len(run) > 1:
                bad = not ((before == "" or before.isspace() or before in OPENERS) and after.isalnum())
            else:
                bad = before.isspace() and bool(line[:s].strip()) and (after == "" or after.isspace())
            if bad:
                out.append(Break(ln, s + 1, len(run), run, f'"{run}" is not permitted'))
    return out


BE = {"be", "am", "is", "are", "was", "were", "been", "being", "ain't", "isn't", "aren't", "wasn't", "weren't"}
FIRST_PERSON = {"i", "me", "my", "mine", "myself", "i'm", "i've", "i'll", "i'd"}


def short_sentences(m):
    return [Break(s[14].line, s[14].col, len(s[14].text), s[14].text,
                  f'"{s[14].text}" is word 15, a sentence may have 14') for s in m.sentences if len(s) > 14]


def no_same_opener(m):
    return [Break(b[0].line, b[0].col, len(b[0].text), b[0].text, f'"{b[0].text}" opens two sentences in a row')
            for a, b in pairwise(m.sentences) if a[0].key == b[0].key]


def short_words(m):
    return [Break(w.line, w.col, len(w.text), w.text, f'"{w.text}" has {w.letters} letters, the limit is 7')
            for w in m.words if w.letters > 7]


def no_repeat_adjacent(m):
    return [Break(b.line, b.col, len(b.text), b.text, f'"{b.text}" repeats the word before it')
            for a, b in pairwise(m.words) if a.key == b.key]


def adjacent(m, same, message):
    return [Break(b.line, b.col, len(b.text), b.text, message(a, b))
            for s in m.sentences for a, b in pairwise(s) if same(a, b)]


def no_alliteration(m):
    return adjacent(m, lambda a, b: a.fold[:1] and a.fold[:1] == b.fold[:1],
                    lambda a, b: f'"{b.text}" starts with the same letter as "{a.text}"')


def no_same_length(m):
    return adjacent(m, lambda a, b: a.letters == b.letters,
                    lambda a, b: f'"{b.text}" has {plural(b.letters, "letter")}, like "{a.text}"')


def even_sentences(m):
    return [Break(s[-1].line, s[-1].col, len(s[-1].text), s[-1].text,
                  f'"{s[-1].text}" is word {len(s)}, the sentence needs an even number')
            for s in m.sentences if len(s) % 2]


def repeats(groups, where):
    out = []
    for g in groups:
        first = {}
        for w in g:
            if w.key in first:
                f = first[w.key]
                out.append(Break(w.line, w.col, len(w.text), w.text, f'"{w.text}" already appears{where} at {f.line}:{f.col}'))
            else:
                first[w.key] = w
    return out


def snowball(m):
    return [Break(w.line, w.col, len(w.text), w.text,
                  f'"{w.text}" has {plural(w.letters, "letter")}, a snowball needs {n} here')
            for s in m.sentences for n, w in enumerate(s, 1) if w.letters != n]


def univocalic(m):
    vowel = next((c for w in m.words for c in w.fold if c in "aeiou"), None)
    out = []
    for w in m.words:
        for i, c in enumerate(w.text):
            other = next((x for x in fold(c) if x in "aeiou" and x != vowel), None)
            if other:
                out.append(Break(w.line, w.col + i, 1, w.text, f'"{w.text}" contains "{other}", the text is in "{vowel}"'))
                break
    return out


def prisoner(m):
    out = []
    for w in m.words:
        for i, c in enumerate(w.text):
            bad = next((x for x in fold(c) if "a" <= x <= "z" and x not in "acemnorsuvwxz"), None)
            if bad:
                out.append(Break(w.line, w.col + i, 1, w.text, f'"{w.text}" contains "{bad}"'))
                break
    return out


# The table. Rotation order is fixed forever; append only, and raise REVISION with any change.

def letter_desc(x):
    return f'No word contains the letter "{x}".'


def letter_def(x):
    return (f'A word breaks this rule when one of its letters, folded, is "{x}". Folding ignores capitalisation, '
            "removes accents and other combining marks, and maps ß to ss, æ to ae, œ to oe, "
            "ø to o, đ to d, ł to l and ı to i, so an accented letter counts as its base "
            "letter. Only the Latin letters a to z take part; other scripts never match. A word breaks the "
            "rule once, with the caret on its first offending letter.")


def letter(rid, x, grade, prefix="", lineage=None):
    return Rule(rid, f"no-{x}", grade, letter_desc(x), prefix + letter_def(x), lineage, False, letter_rule(x))


TABLE = [
    Rule("R01", "no-dash", "plain",
         "No em dash, en dash, horizontal bar, doubled hyphen or spaced hyphen used as a dash.",
         "A break is any run that holds an em dash, an en dash or a horizontal bar (U+2014, U+2013, U+2015, "
         "and the two-em and three-em dashes), a run of two or more hyphens, or a single hyphen with whitespace "
         "on both sides after other text on the line. A run of hyphens that opens a word (after whitespace, the "
         "start of a line, or an opening quote, bracket or backtick) and is followed by a letter or digit is a "
         "command line flag, such as --force, and is fine. A hyphen inside a word or between digits "
         "(well-known, 10-20) is fine, and so is a hyphen that opens a line, as in a list.",
         None, False, no_dash),
    Rule("R02", "no-the", "effort", 'The word "the" does not appear.',
         'A word breaks this rule when it is "the", in any capitalisation.',
         None, False, lambda m: forbidden(m, lambda w: w.key == "the")),
    Rule("R03", "no-exclaim", "plain", "No exclamation mark.",
         "A break is any run of exclamation marks (! or the full-width ！). A run counts once.",
         None, False, lambda m: marks(m, "[!！]+")),
    letter("R04", "k", "effort"),
    Rule("R05", "short-sentences", "plain", "No sentence has more than 14 words.",
         "A sentence breaks this rule when it has more than 14 words. The caret sits on word 15. Numbers "
         "and punctuation are not words.",
         None, True, short_sentences),
    Rule("R06", "no-first-person", "effort", "None of: i, me, my, mine, myself, i'm, i've, i'll, i'd.",
         "A word breaks this rule when it is one of i, me, my, mine, myself, i'm, i've, i'll or i'd, in any "
         "capitalisation. A typographic apostrophe counts as a plain one.",
         None, False, lambda m: forbidden(m, lambda w: w.key in FIRST_PERSON)),
    Rule("R07", "no-numerals", "plain", "No digits; spell numbers out.",
         "A break is any number: a run of decimal digits in any script, with a single . or , allowed "
         "between two digits.",
         None, False, lambda m: [Break(n.line, n.col, len(n.text), n.text, f'"{n.text}" is not permitted')
                                 for n in m.numbers]),
    Rule("R08", "no-be", "effort", 'No form of "to be".',
         "E-Prime: English without the verb to be. A word breaks this rule when it is be, am, is, are, was, "
         "were, been, being, ain't, isn't, aren't, wasn't or weren't, or when it ends in 're or 'm. A word "
         "ending in 's is never flagged, because the 's may be a possessive.",
         "E-Prime, D. David Bourland Jr.", False,
         lambda m: forbidden(m, lambda w: w.key in BE or w.key.endswith(("'re", "'m")))),
    Rule("R09", "no-contractions", "plain", "No word ending in n't, 'll, 're, 've, 'm or 'd, and no \"let's\".",
         "A word breaks this rule when it ends in n't, 'll, 're, 've, 'm or 'd, or when it is let's. A word "
         "ending in 's is not flagged, because the 's may be a possessive.",
         None, False,
         lambda m: forbidden(m, lambda w: w.key == "let's" or w.key.endswith(("n't", "'ll", "'re", "'ve", "'m", "'d")))),
    letter("R10", "w", "effort"),
    Rule("R11", "no-same-opener", "plain", "No two consecutive sentences open with the same word.",
         "A sentence breaks this rule when its first word is the first word of the sentence before it, in "
         "any capitalisation. The caret sits on the second opener.",
         None, True, no_same_opener),
    Rule("R12", "short-words", "effort", "No word has more than 7 letters.",
         "A word breaks this rule when it has more than 7 letters. Apostrophes and combining marks are not "
         "letters.",
         None, False, short_words),
    Rule("R13", "no-repeat-adjacent", "plain", "No word immediately repeats the word before it.",
         "A word breaks this rule when it is the same word as the word before it, in any capitalisation, "
         "across a line break or a sentence end too. Numbers are not words and do not separate them.",
         None, False, no_repeat_adjacent),
    Rule("R14", "no-alliteration", "effort", "Two adjacent words in a sentence do not start with the same letter.",
         "Two adjacent words in one sentence break this rule when they start with the same letter after "
         "folding (capitalisation and accents ignored). The caret sits on the second word.",
         None, True, no_alliteration),
    Rule("R15", "no-ly", "plain", 'No word of three or more letters ends in "ly".',
         'A word of three or more letters breaks this rule when it ends in "ly". The rule is mechanical on '
         "purpose: family, only and fly break it too.",
         None, False, lambda m: forbidden(m, lambda w: w.letters >= 3 and w.key.endswith("ly"))),
    letter("R16", "y", "effort"),
    Rule("R17", "even-sentences", "effort", "Every sentence has an even number of words.",
         "A sentence breaks this rule when it has an odd number of words. The caret sits on its last word.",
         None, True, even_sentences),
    Rule("R18", "no-and", "effort", 'Neither the word "and" nor "&".',
         'A break is the word "and", in any capitalisation, or any run of ampersands.',
         None, False, lambda m: forbidden(m, lambda w: w.key == "and") + marks(m, "&+")),
    letter("R19", "v", "effort"),
    Rule("R20", "no-repeat-sentence", "effort", "No word appears twice in one sentence.",
         "A word breaks this rule when the same word has already appeared in the same sentence, in any "
         "capitalisation. Every later occurrence is a break, and the message gives the line and column of "
         "the first.",
         None, True, lambda m: repeats(m.sentences, " in this sentence")),
    letter("R21", "b", "effort"),
    Rule("R22", "no-same-length", "effort",
         "Two adjacent words in a sentence do not have the same number of letters.",
         "Two adjacent words in one sentence break this rule when they have the same number of letters. "
         "Apostrophes and combining marks are not letters. The caret sits on the second word.",
         None, True, no_same_length),
    letter("R23", "g", "effort"),
    Rule("R24", "no-repeated-word", "effort", "No word appears twice anywhere in the text.",
         "A word breaks this rule when the same word has already appeared anywhere in the text, in any "
         "capitalisation. Every later occurrence is a break, and the message gives the line and column of "
         "the first.",
         None, False, lambda m: repeats([m.words], "")),
    letter("R25", "e", "hard", "Lipogram. ", "Perec, La Disparition, 1969"),
    letter("R26", "a", "hard", "Lipogram. ", "Oulipo lipogram"),
    letter("R27", "t", "hard", "Lipogram. ", "Oulipo lipogram"),
    Rule("R28", "snowball", "hard", "In every sentence the word in position n has exactly n letters.",
         "Snowball. In every sentence the first word has 1 letter, the second 2, the third 3, and so on. "
         "Every word of the wrong length is a break.",
         "Oulipo snowball", True, snowball),
    Rule("R29", "univocalic", "hard", "The whole text uses one vowel only.",
         "Univocalism. The whole text uses one vowel only, out of a, e, i, o and u; y is a consonant. The "
         "vowel is the first one the text uses. A word that contains another vowel breaks the rule, with the "
         "caret on that vowel; a word with no vowel passes. Letters are folded, so an accented vowel counts "
         "as its base vowel.",
         "Perec, Les Revenentes, 1972 (e only); Oulipo univocalism", False, univocalic),
    Rule("R30", "prisoner", "hard", "Only letters without ascenders or descenders: a c e m n o r s u v w x z.",
         "The prisoner's constraint. Only the letters a c e m n o r s u v w x z are allowed. A word breaks "
         "the rule at its first other Latin letter, one of b d f g h i j k l p q t y. Letters are folded, so "
         "an accented letter counts as its base letter.",
         "Oulipo prisoner's constraint", False, prisoner),
]
ROTATION = [r for r in TABLE if r.grade != "hard"]
HARD = [r for r in TABLE if r.grade == "hard"]
SENTENCES = ("A sentence ends at a run of . ! ? … 。 ！ ？ followed by whitespace or the end of "
             "the text, with closing quotes or brackets allowed in between, and at a blank line. A line break "
             "alone does not end a sentence. A period after mr, mrs, ms, dr, prof, st, vs, cf, e.g, i.e or a "
             "single letter does not end one.")


def lookup(name):
    for r in TABLE:
        if r.name == name:
            return r
    if re.fullmatch("no-[a-z]", name):
        x = name[3]
        return Rule(None, name, None, letter_desc(x), letter_def(x), None, False, letter_rule(x))
    raise Fail(f'rule: error: unknown rule "{name}"; see rule --list')


def days(d):
    return (d - EPOCH).days


def rule_for(d):
    return ROTATION[days(d) % len(ROTATION)]


def parse_date(s):
    try:
        if re.fullmatch("[0-9]{4}-[0-9]{2}-[0-9]{2}", s):
            return date.fromisoformat(s)
    except ValueError:
        pass
    raise Fail(f'rule: error: bad date "{s}"; use YYYY-MM-DD')


# The surfaces

def report(name, m, rule, breaks, out, color):
    for b in sorted(breaks, key=lambda b: (b.line, b.col)):
        line = m.lines[b.line - 1]
        pad = "".join("\t" if c == "\t" else " " for c in line[:b.col - 1])
        err, mark = "error:", "^" + "~" * (b.length - 1)
        if color:
            err, mark = BRICK + err + RESET, BRICK + mark + RESET
        out.write(f"{name}:{b.line}:{b.col}: {err} {b.message} [{rule.name}]\n{line}\n{pad}{mark}\n")
    n = len(breaks)
    out.write(f"{plural(n, 'error')} generated.\n")


def catalogue():
    nw = max(len(r.name) for r in TABLE)
    gw = max(len(r.grade) for r in TABLE)
    rows = [f"Rotation table, revision {REVISION}. In force from {EPOCH}. "
            f"{len(ROTATION)} daily rules, {len(HARD)} by name.", ""]
    for r in TABLE:
        when = "daily  " if r in ROTATION else "by name"
        rows += [f"{r.id}  {r.name:<{nw}}  {r.grade:<{gw}}  {when}  {r.lineage or '-'}", f"     {r.desc}"]
    return "\n".join(rows + ["", "no-<letter> is accepted for any letter a to z."])


def explain(r, today):
    head = "  ".join(x for x in (r.id, r.name, r.grade, "daily" if r in ROTATION else "by name") if x)
    paras = [r.definition] + ([SENTENCES] if r.sentences else [])
    if r in ROTATION:
        i, d = ROTATION.index(r), days(today)
        paras.append(f"By date: drawn when the number of days since {EPOCH}, counted modulo {len(ROTATION)}, is {i}.")
        n = (d - i) // len(ROTATION) + 1 if d >= i else 0
        closing = f"In force on {plural(n, 'day')} since {EPOCH}."
    else:
        closing = "Never in force by date."
    rows = [head, "", r.desc] + [x for p in paras for x in ("", textwrap.fill(p, 72))]
    if r.lineage:
        rows += ["", f"Lineage: {r.lineage}."]
    return "\n".join(rows + ["", closing])


LOG_LINE = re.compile("([0-9]{4}-[0-9]{2}-[0-9]{2}) ([a-z-]+) ([01]) ([0-9]+) ([0-9]+)")


def log_path():
    if os.environ.get("RULE_LOG"):
        return os.environ["RULE_LOG"]
    state = os.environ.get("XDG_STATE_HOME") or os.path.join(os.path.expanduser("~"), ".local", "state")
    return os.path.join(state, "rule-of-the-day", "log")


def record():
    path = log_path()
    try:
        with open(path, encoding="utf-8") as f:
            rows = [m.groups() for m in map(LOG_LINE.fullmatch, f.read().splitlines()) if m]
    except FileNotFoundError:
        rows = []
    except (OSError, UnicodeDecodeError) as e:
        raise Fail(f"rule: error: {path}: {getattr(e, 'strerror', None) or 'not valid UTF-8'}")
    if not rows:
        return "No days on record."
    status = ["survived" if code == "0" else "broke" for _, _, code, _, _ in rows]
    nw, sw = max(len(r[1]) for r in rows), max(map(len, status))
    ww, bw = max(len(r[3]) for r in rows), max(len(r[4]) for r in rows)
    out, survived = [], {}
    for (d, name, code, words, breaks), st in zip(rows, status):
        out.append(f"{d}  {name:<{nw}}  {st:<{sw}}  {breaks:>{bw}} of {words:>{ww}} {'word' if words == '1' else 'words'}")
        survived[d] = survived.get(d, False) or code == "0"
    out.append(f"Survived {sum(survived.values())} of {plural(len(survived), 'day')} on record.")
    return "\n".join(out)


HELP = """\
usage: rule [--rule NAME] [--date YYYY-MM-DD] [--no-log] FILE
       rule [--date YYYY-MM-DD]
       rule --list
       rule --explain NAME [--date YYYY-MM-DD]
       rule --record
       rule --help

Checks FILE against one writing rule and reports every break the way a
compiler reports an error. FILE "-" reads standard input. With no FILE,
prints the rule for the date.

  --rule NAME        check against the rule NAME instead of the date's
  --date YYYY-MM-DD  use the rule for that date instead of today's
  --no-log           do not record this run
  --list             print the 30 named rules
  --explain NAME     print the exact definition of one rule
  --record           print the log and the tally
  --help             print this help

Exit status: 0 the text kept the rule, 1 it broke the rule, 2 the tool
could not run. Errors go to standard error. A text that keeps the rule
prints nothing.

A check of today's rule, without --rule or --date, appends one line to
$RULE_LOG, else $XDG_STATE_HOME/rule-of-the-day/log, else
~/.local/state/rule-of-the-day/log. The checked file is never written.

Rules are drawn from a fixed table. A given date always gives the same rule. There is no way to ignore a rule."""


def parse(argv):
    opts = {"rule": None, "date": None, "explain": None, "no-log": False, "list": False, "record": False,
            "help": False}
    files, args = [], iter(argv)
    for a in args:
        if a == "-" or not a.startswith("-"):
            files.append(a)
            continue
        if a == "--":
            files.extend(args)
            break
        key, eq, value = a.partition("=")
        if key in ("--rule", "--date", "--explain"):
            if not eq:
                value = next(args, None)
                if value is None:
                    raise Fail(f"rule: error: {key} needs a value; see rule --help")
            opts[key[2:]] = value
        elif key in ("--no-log", "--list", "--record", "--help", "-h") and not eq:
            opts["help" if key == "-h" else key[2:]] = True
        else:
            raise Fail(f'rule: error: unknown option "{a}"; see rule --help')
    return opts, files


def read(path):
    name = "<stdin>" if path == "-" else path
    try:
        if path == "-":
            data = sys.stdin.buffer.read()
        else:
            with open(path, "rb") as f:
                data = f.read()
    except OSError as e:
        raise Fail(f"rule: error: {path}: {e.strerror}")
    try:
        return name, data.decode("utf-8")
    except UnicodeDecodeError:
        raise Fail(f"rule: error: {name}: not valid UTF-8")


def run(argv):
    opts, files = parse(argv)
    if opts["help"]:
        print(HELP)
        return 0
    today = parse_date(opts["date"]) if opts["date"] else date.today()
    if opts["list"]:
        print(catalogue())
        return 0
    if opts["explain"]:
        print(explain(lookup(opts["explain"]), today))
        return 0
    if opts["record"]:
        print(record())
        return 0
    if len(files) > 1:
        raise Fail("rule: error: one FILE at a time; see rule --help")
    rule = lookup(opts["rule"]) if opts["rule"] else rule_for(today)
    if not files:
        if opts["rule"]:
            raise Fail('rule: error: --rule needs a FILE ("-" reads stdin); see rule --help')
        print(f"{today}  {rule.name}  {rule.grade}\n{rule.desc}")
        return 0
    name, text = read(files[0])
    m = model(text)
    if not m.words:
        raise Fail(f"{name}: error: no words to check")
    breaks = rule.check(m)
    if breaks:
        report(name, m, rule, breaks, sys.stderr, sys.stderr.isatty() and "NO_COLOR" not in os.environ)
    code = 1 if breaks else 0
    if not (opts["rule"] or opts["date"] or opts["no-log"]):
        path = log_path()
        try:
            os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
            with open(path, "a", encoding="utf-8") as f:
                f.write(f"{today} {rule.name} {code} {len(m.words)} {len(breaks)}\n")
        except OSError as e:
            raise Fail(f"rule: error: {path}: {e.strerror}")
    return code


def main(argv=None):
    try:
        return run(sys.argv[1:] if argv is None else argv)
    except Fail as e:
        print(e, file=sys.stderr)
        return 2


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BrokenPipeError:  # rule --list | head
        os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        sys.exit(1)
