"""Tests for rule.py. Run: uv run python -m unittest -v

Every text in this file is a test fixture, written for these tests. None of it is real data.
The fixtures retell one anecdote (a Sunday walk to a river) under each rule, after Queneau's
Exercices de style. A rule enters the rotation only if a paragraph of at least 40 words of
ordinary English keeps it.
"""

import contextlib
import hashlib
import io
import os
import re
import tempfile
import unittest
from datetime import date
from unittest import mock

import rule

# Fixture: the anecdote as first told. It keeps the rules it is listed under in DAILY.
B = ("We left the house early on Sunday morning and walked down to the river. The water was high after a "
     "week of rain, and the path along the bank was soft. A few people were fishing near the old bridge, "
     "and nobody said much. We stayed until noon and then went home for lunch.")

# Fixtures: rule name -> (a paragraph that keeps it, a sentence that breaks it once, column, message).
DAILY = {
    "no-dash": (B, "We waited -- then left.", 11, '"--" is not permitted'),
    "no-the": ("We left our house early on Sunday morning and walked down to a river. Its water was high after "
               "a week of rain, and a path along its bank was soft. A few people were fishing near an old bridge, "
               "and nobody said much. We stayed until noon and then went home for lunch.",
               "We walked to the market.", 14, '"the" is not permitted'),
    "no-exclaim": (B, "Stop that at once!", 18, '"!" is not permitted'),
    "no-k": ("We left the house early on Sunday morning and went down to the river. The water was high after two "
             "days of rain, and the path along the shore was soft. A few people were fishing near the old bridge, "
             "and nobody said much. We stayed until noon and then went home for lunch.",
             "A kick.", 3, '"kick" contains "k"'),
    "short-sentences": ("We left the house early on Sunday morning. We walked down to the river. The water was high "
                        "after a week of rain. The path along the bank was soft. A few people were fishing near "
                        "the old bridge. Nobody said much. We stayed until noon. Then we went home for lunch.",
                        "On Sunday we walked along the narrow path, past the old mill and the pond, to the garden.",
                        70, '"pond" is word 15, a sentence may have 14'),
    "no-first-person": (B, "Yesterday I walked home.", 11, '"I" is not permitted'),
    "no-numerals": (B, "We moved here in 2026.", 18, '"2026" is not permitted'),
    "no-be": ("We left the house early on Sunday morning and walked down to the river. The water ran high after a "
              "week of rain, and the path along the bank felt soft. A few people sat fishing near the old bridge, "
              "and nobody said much. We stayed until noon and then went home for lunch.",
              "The door was open.", 10, '"was" is not permitted'),
    "no-contractions": (B, "We don't know yet.", 4, '"don\'t" is not permitted'),
    "no-w": ("They left the house early on Sunday morning and strolled along to the river. It ran high after a long "
             "spell of rain, and the path along the bank felt soft. A couple of people sat fishing near the old "
             "bridge, and nobody said much. They stayed until noon and then headed home for lunch.",
             "Snow fell all night.", 4, '"Snow" contains "w"'),
    "no-same-opener": (B, "The door opened. The cat came in.", 18, '"The" opens two sentences in a row'),
    "short-words": (B, "We left yesterday.", 9, '"yesterday" has 9 letters, the limit is 7'),
    "no-repeat-adjacent": (B, "We walked to the the market.", 18, '"the" repeats the word before it'),
    "no-alliteration": ("We left our house early on Sunday morning. Heavy rain had fallen all week, so the river looked "
                        "high. A few people sat fishing near an old bridge. Nobody said very much. We stayed until "
                        "noon, then went home for lunch.",
                        "It was the time of year.", 12, '"time" starts with the same letter as "the"'),
    "no-ly": ("We left the house at dawn on Sunday and walked down to the river. The water was high after a week of "
              "rain, and the path along the bank was soft. A few people were fishing near the old bridge, and "
              "nobody said much. We stayed until noon and then went home for lunch.",
              "She walked slowly home.", 12, '"slowly" is not permitted'),
    "no-y": ("We left the house at dawn on a cold morning and walked down to the river. The water was high after a "
             "week of rain, and the path along the bank was soft. A few people were fishing near the old bridge, "
             "and none of them said much. We came home at noon for lunch.",
             "We stayed home.", 7, '"stayed" contains "y"'),
    "even-sentences": ("We left the house early on Sunday morning. The river ran high after a long week of rain. A "
                       "few people sat fishing near the old stone bridge. Nobody said very much. We stayed until "
                       "noon and then went home for lunch.",
                       "We found that the old garden gate was open.", 39,
                       '"open" is word 9, the sentence needs an even number'),
    "no-and": ("We left the house early on Sunday morning, walking down to the river. The water was high after a "
               "week of rain, so the path along the bank was soft. A few people were fishing near the old bridge. "
               "Nobody said much. We stayed until noon, then went home for lunch.",
               "Salt and pepper.", 6, '"and" is not permitted'),
    "no-v": ("We left the house early on Sunday morning and walked down to the lake. The water was high after a week "
             "of rain, and the path along the shore was soft. A few people were fishing near the old bridge, and "
             "nobody said much. We stayed until noon and then went home for lunch.",
             "The river rose.", 7, '"river" contains "v"'),
    "no-repeat-sentence": ("We left our house early on Sunday morning and walked down to the river. Its water ran high "
                           "after a week of rain, so every path felt soft underfoot. A few people were fishing near "
                           "an old bridge, and nobody said much. We stayed until noon, then went home for lunch.",
                           "The dog chased the cat.", 16, '"the" already appears in this sentence at 1:1'),
    "no-b": ("We left the house early on Sunday morning and walked down to the river. The water was high after a "
             "week of rain, and the path along the shore was soft. A few people were fishing near the old mill, "
             "and none of them said much. We stayed until noon and then went home for lunch.",
             "We sat by the stream.", 8, '"by" contains "b"'),
    "no-same-length": ("We walked to a river on Sunday morning. Its water ran high after a week of heavy rain. A few "
                       "people sat fishing near an old stone bridge. Nobody said a word. We stayed until noon and "
                       "then walked home for lunch.",
                       "Leave the gate open.", 16, '"open" has 4 letters, like "gate"'),
    "no-g": ("We left the house early on Sunday and walked down to the river. The water had risen after a week of "
             "rain, and the path on the bank was soft. A few people sat with their rods near the old mill, and "
             "nobody said much. We stayed until noon and then went home for lunch.",
             "The dog slept.", 7, '"dog" contains "g"'),
    "no-repeated-word": ("Early on Sunday morning we left our house and walked down to the river. Its water ran high "
                         "after a week of rain, so every path felt soft underfoot. Several people were fishing near "
                         "an old bridge; nobody said much. Around noon, hungry, everyone went home for lunch.",
                         "The cat saw the dog.", 13, '"the" already appears at 1:1'),
}

# Fixtures for the six rules that are never drawn by date: at least 8 words that keep it, one break.
HARD = {
    "no-e": ("On Sunday morning, both of us took a walk down to a stony brook. It was high, as rain had not quit "
             "for days, and our path was soft. A handful of folks sat fishing by an old mill, saying nothing. At "
             "noon, both of us got back for lunch.",
             "The cat sat.", 3, '"The" contains "e"'),
    "no-a": ("We left our house one morning, then went down to the river. It stood high from recent storms, so the "
             "riverside turf felt soft. Some people were fishing by the old bridge; no one spoke much. We stood "
             "there until noon, then went home for lunch.",
             "The cat slept.", 6, '"cat" contains "a"'),
    "no-t": ("On Sunday morning we came down from our house, walking along by a river. Rain all week had made a bog "
             "of every lane. A handful of people were fishing by an old bridge; nobody said much. We remained close "
             "by, and around midday we came home for lunch.",
             "A cat ran.", 5, '"cat" contains "t"'),
    "snowball": ("I am out near water. I am not cold.", "I am best.", 6, '"best" has 4 letters, a snowball needs 3 here'),
    "univocalic": ("At dawn a man and a lass walk past a damp canal. Lads stand at a bank as a man casts and a lass "
                   "claps.",
                   "A bad man had men.", 16, '"men" contains "e", the text is in "a"'),
    "prisoner": ("On a warm summer morn we came near a narrow mere, so we saw some swans.",
                 "The man ran.", 1, '"The" contains "t"'),
}

ROTATION = ["no-dash", "no-the", "no-exclaim", "no-k", "short-sentences", "no-first-person", "no-numerals", "no-be",
            "no-contractions", "no-w", "no-same-opener", "short-words", "no-repeat-adjacent", "no-alliteration",
            "no-ly", "no-y", "even-sentences", "no-and", "no-v", "no-repeat-sentence", "no-b", "no-same-length",
            "no-g", "no-repeated-word"]


class TTY(io.StringIO):
    def isatty(self):
        return True


def run(*argv, stdin=b"", env=None, tty=False):
    out, err = io.StringIO(), (TTY() if tty else io.StringIO())
    fake_stdin = io.TextIOWrapper(io.BytesIO(stdin))
    with mock.patch.dict(os.environ, env or {}), mock.patch("sys.stdin", fake_stdin), \
            contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
        code = rule.main(list(argv))
    return code, out.getvalue(), err.getvalue()


def check(name, text):
    return run("--rule", name, "-", stdin=text.encode())


def setUpModule():
    # No test may touch a real log.
    global LOGDIR
    LOGDIR = tempfile.TemporaryDirectory()
    patcher = mock.patch.dict(os.environ, {"RULE_LOG": os.path.join(LOGDIR.name, "log")})
    patcher.start()
    unittest.addModuleCleanup(patcher.stop)
    unittest.addModuleCleanup(LOGDIR.cleanup)


class Survivability(unittest.TestCase):
    """For each rule: a paragraph keeps it in silence, a sentence breaks it at the expected word and column."""

    def keeps(self, name, text, minimum):
        self.assertGreaterEqual(len(text.split()), minimum)
        self.assertEqual(check(name, text), (0, "", ""))

    def breaks(self, name, sentence, col, message):
        code, out, err = check(name, sentence)
        lines = err.splitlines()
        word = message.split('"')[1]
        mark = "^" if ' contains "' in message else "^" + "~" * (len(word) - 1)
        self.assertEqual((code, out), (1, ""))
        self.assertEqual(lines, [f"<stdin>:1:{col}: error: {message} [{name}]", sentence,
                                 " " * (col - 1) + mark, "1 error generated."])
        self.assertTrue(sentence[col - 1:].startswith(word) or ' contains "' in message)


def add(name, fixture, minimum):
    text, sentence, col, message = fixture
    r = rule.lookup(name)
    slug = f"test_{r.id}_{name.replace('-', '_')}"
    setattr(Survivability, f"{slug}_paragraph_passes", lambda self: self.keeps(name, text, minimum))
    setattr(Survivability, f"{slug}_sentence_breaks", lambda self: self.breaks(name, sentence, col, message))


for _name, _fixture in DAILY.items():
    add(_name, _fixture, 40)
for _name, _fixture in HARD.items():
    add(_name, _fixture, 8)


class Table(unittest.TestCase):
    def test_rotation_order_is_fixed(self):
        self.assertEqual([r.name for r in rule.ROTATION], ROTATION)
        self.assertEqual(sorted(DAILY), sorted(ROTATION))
        self.assertEqual(sorted(HARD), sorted(r.name for r in rule.HARD))

    def test_grades_alternate(self):
        grades = [r.grade for r in rule.ROTATION]
        self.assertEqual((grades.count("plain"), grades.count("effort")), (8, 16))
        self.assertEqual([i for i, g in enumerate(grades) if g == "plain"], list(range(0, 15, 2)))
        self.assertTrue(all(g == "effort" for g in grades[15:]))
        self.assertTrue(all(r.grade == "hard" for r in rule.HARD))

    def test_list(self):
        code, out, _ = run("--list")
        lines = out.splitlines()
        self.assertEqual(code, 0)
        self.assertEqual(lines[0], "Rotation table, revision 1. In force from 1970-01-01. 24 daily rules, 6 by name.")
        self.assertEqual(lines[0], f"Rotation table, revision 1. In force from 1970-01-01. "
                                   f"{len(rule.ROTATION)} daily rules, {len(rule.HARD)} by name.")
        self.assertEqual(len([x for x in lines if re.match(r"R\d\d  [a-z-]+ ", x)]), 30)
        self.assertEqual(lines[-1], "no-<letter> is accepted for any letter a to z.")

    def test_letter_rules_share_one_description(self):
        for x in "kwyvbgeat":
            self.assertEqual(rule.lookup(f"no-{x}").desc, f'No word contains the letter "{x}".')
        self.assertEqual(rule.lookup("no-q").desc, 'No word contains the letter "q".')
        for bad in ("no-5", "no-é", "no-", "no-kk", "No-k"):
            self.assertEqual(run("--rule", bad, "-", stdin=b"x")[0], 2)
            self.assertIn("unknown rule", run("--explain", bad)[2])


class Calendar(unittest.TestCase):
    def day(self, d):
        code, out, err = run("--date", d)
        self.assertEqual((code, err), (0, ""))
        return out.splitlines()

    def test_known_dates(self):
        for d, name in [("1970-01-01", "no-dash"), ("1970-01-02", "no-the"), ("1969-12-31", "no-repeated-word"),
                        ("2026-10-13", "no-k"), ("2026-10-14", "short-sentences")]:
            self.assertEqual(self.day(d)[0].split("  ")[:2], [d, name])
        self.assertEqual(self.day("2026-10-13"), ["2026-10-13  no-k  effort", 'No word contains the letter "k".'])

    def test_any_24_consecutive_days(self):
        start = date(2026, 10, 1).toordinal()
        lines = [self.day(date.fromordinal(start + i).isoformat())[0].split("  ") for i in range(24)]
        self.assertEqual(len({n for _, n, _ in lines}), 24)
        self.assertNotIn("hard", {g for _, _, g in lines})

    def test_bad_date(self):
        for d in ("2100-02-30", "2026-13-01", "20261013", "yesterday"):
            code, out, err = run("--date", d)
            self.assertEqual((code, out), (2, ""))
            self.assertIn("bad date", err)

    def test_explain_closing_line(self):
        def last(name, d):
            return run("--explain", name, "--date", d)[1].splitlines()[-1]
        self.assertEqual(last("no-dash", "1970-01-24"), "In force on 1 day since 1970-01-01.")
        self.assertEqual(last("no-repeated-word", "1970-01-24"), "In force on 1 day since 1970-01-01.")
        self.assertEqual(last("no-dash", "1970-01-25"), "In force on 2 days since 1970-01-01.")
        self.assertEqual(last("no-the", "1970-01-01"), "In force on 0 days since 1970-01-01.")
        self.assertEqual(last("snowball", "2026-10-13"), "Never in force by date.")
        self.assertEqual(last("no-q", "2026-10-13"), "Never in force by date.")


class Tokenizer(unittest.TestCase):
    def test_words_and_numbers(self):
        m = rule.model("A well-known b2b don’t naïve rock'n'roll 3.14 1,000 x_y a/b 'quoted' 1.2.")
        self.assertEqual([w.text for w in m.words],
                         ["A", "well", "known", "b", "b", "don’t", "naïve", "rock'n'roll", "x", "y", "a",
                          "b", "quoted"])
        self.assertEqual([n.text for n in m.numbers], ["2", "3.14", "1,000", "1.2"])
        self.assertEqual([w.letters for w in m.words[5:7]], [4, 5])
        self.assertEqual(m.words[5].key, "don't")

    def test_folding(self):
        self.assertEqual(rule.fold("Straße Æsop Œuvre Øre Đó Łódź "
                                   "ışık Çağrı İz café"),
                         "strasse aesop oeuvre ore do lodz isik cagri iz cafe")

    def test_sentences(self):
        def sentences(text):
            return [" ".join(w.text for w in s) for s in rule.model(text).sentences]
        self.assertEqual(sentences("Mr. Smith met Dr. J. Watson. (E.g. this.) It cost 3.50 today! Why?\" Done"),
                         ["Mr Smith met Dr J Watson", "E g this", "It cost today", "Why", "Done"])
        self.assertEqual(sentences("one line\nstill one\n\nnew one\n   \nlast"),
                         ["one line still one", "new one", "last"])
        self.assertEqual(sentences("Wait… Then. 「你好。」No... yes?! ok"),
                         ["Wait", "Then", "你好 No", "yes", "ok"])

    def test_cjk_is_one_word(self):
        self.assertEqual([w.text for w in rule.model("今日は晴れ").words],
                         ["今日は晴れ"])


class Report(unittest.TestCase):
    VOILA = "Voilà le café de la forêt."
    EXPECTED = ['<stdin>:1:8: error: "le" contains "e" [no-e]', VOILA, "       ^",
                '<stdin>:1:13: error: "café" contains "e" [no-e]', VOILA, " " * 12 + "^",
                '<stdin>:1:16: error: "de" contains "e" [no-e]', VOILA, " " * 15 + "^",
                '<stdin>:1:24: error: "forêt" contains "e" [no-e]', VOILA, " " * 23 + "^",
                "4 errors generated."]

    def test_unicode_columns(self):
        import unicodedata
        for text in (self.VOILA + "\n", self.VOILA + "\r\n", unicodedata.normalize("NFD", self.VOILA),
                     "\ufeff" + self.VOILA):
            code, out, err = check("no-e", text)
            self.assertEqual((code, out, err.splitlines()), (1, "", self.EXPECTED))

    def test_tab_padding(self):
        code, _, err = check("no-e", "\t" + self.VOILA)
        self.assertEqual(err.splitlines()[2], "\t       ^")

    def test_walked_market_and_kick(self):
        code, _, err = check("no-k", "We walked to the market.\n")
        self.assertEqual((code, err.splitlines()), (1, [
            '<stdin>:1:7: error: "walked" contains "k" [no-k]', "We walked to the market.", "      ^",
            '<stdin>:1:21: error: "market" contains "k" [no-k]', "We walked to the market.", " " * 20 + "^",
            "2 errors generated."]))
        self.assertEqual(check("no-k", "A kick.")[2].splitlines(),
                         ['<stdin>:1:3: error: "kick" contains "k" [no-k]', "A kick.", "  ^", "1 error generated."])

    def test_dash(self):
        code, _, err = check("no-dash", "one -- two\nthree \u2014 four\n")
        self.assertEqual((code, err.splitlines()), (1, [
            '<stdin>:1:5: error: "--" is not permitted [no-dash]', "one -- two", "    ^~",
            '<stdin>:2:7: error: "\u2014" is not permitted [no-dash]', "three \u2014 four", "      ^",
            "2 errors generated."]))
        self.assertEqual(check("no-dash", "run it with --force now\nwell-known and 10-20\n- a list item\n"
                                          "see (`--rule` and \"--date\")\n"), (0, "", ""))
        breaks = [b.word for b in rule.lookup("no-dash").check(rule.model("a - b c--d e \u2013 f g ---\nh\u2013i -"))]
        self.assertEqual(breaks, ["-", "--", "\u2013", "---", "\u2013", "-"])

    def test_colour_only_on_tty_without_no_color(self):
        brick, reset = "\x1b[38;2;236;94;82m", "\x1b[0m"
        with mock.patch.dict(os.environ):
            os.environ.pop("NO_COLOR", None)
            _, _, err = run("--rule", "no-the", "-", stdin=b"See the sea.", tty=True)
        self.assertEqual(err.splitlines(), [f'<stdin>:1:5: {brick}error:{reset} "the" is not permitted [no-the]',
                                            "See the sea.", f"    {brick}^~~{reset}", "1 error generated."])
        self.assertEqual(len(re.findall("\x1b", err)), 4)
        _, _, err = run("--rule", "no-the", "-", stdin=b"See the sea.", tty=True, env={"NO_COLOR": "1"})
        self.assertNotIn("\x1b", err)
        self.assertNotIn("\x1b", check("no-the", "See the sea.")[2])

    def test_rule_messages(self):
        def first(name, text):
            return check(name, text)[2].splitlines()[0]
        self.assertEqual(first("no-first-person", "So I’m here."), '<stdin>:1:4: error: "I’m" is not permitted [no-first-person]')
        self.assertEqual(first("no-be", "They're out."), '<stdin>:1:1: error: "They\'re" is not permitted [no-be]')
        self.assertEqual(check("no-be", "The dog's bone, it's here now."), (0, "", ""))
        self.assertEqual(first("no-exclaim", "No!!! Fine."), '<stdin>:1:3: error: "!!!" is not permitted [no-exclaim]')
        self.assertEqual(first("no-and", "Salt & pepper."), '<stdin>:1:6: error: "&" is not permitted [no-and]')
        self.assertEqual(first("no-ly", "The fly."), '<stdin>:1:5: error: "fly" is not permitted [no-ly]')
        self.assertEqual(first("prisoner", "a moon. a hat."), '<stdin>:1:11: error: "hat" contains "h" [prisoner]')
        self.assertEqual(first("snowball", "A cat."), '<stdin>:1:3: error: "cat" has 3 letters, a snowball needs 2 here [snowball]')
        self.assertEqual(first("no-same-length", "I a."), '<stdin>:1:3: error: "a" has 1 letter, like "I" [no-same-length]')
        self.assertEqual(check("no-s", "Straße")[2].splitlines()[0], '<stdin>:1:1: error: "Straße" contains "s" [no-s]')
        self.assertEqual(check("no-s", "groß")[2].splitlines()[0], '<stdin>:1:4: error: "groß" contains "s" [no-s]')
        self.assertEqual(check("no-e", "Αθήνα мед"), (0, "", ""))


class Log(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.TemporaryDirectory()
        self.addCleanup(self.dir.cleanup)
        self.log = os.path.join(self.dir.name, "state", "log")
        self.env = {"RULE_LOG": self.log}
        today = rule.rule_for(date.today())
        self.today, (self.keep, self.broken, _, _) = today, DAILY[today.name]

    def file(self, text, name="draft.txt"):
        path = os.path.join(self.dir.name, name)
        with open(path, "wb") as f:
            f.write(text if isinstance(text, bytes) else text.encode())
        return path

    def lines(self):
        with open(self.log) as f:
            return f.read().splitlines()

    def test_ritual_run_is_logged_once(self):
        draft = self.file(self.keep)
        self.assertEqual(run(draft, env=self.env), (0, "", ""))
        words = len(rule.model(self.keep).words)
        self.assertEqual(self.lines(), [f"{date.today()} {self.today.name} 0 {words} 0"])
        run("--rule", "no-the", draft, env=self.env)
        run("--date", "2030-01-01", draft, env=self.env)
        run("--no-log", draft, env=self.env)
        run(os.path.join(self.dir.name, "nope.txt"), env=self.env)
        self.assertEqual(len(self.lines()), 1)
        code, _, err = run(self.file(self.broken, "broken.txt"), env=self.env)
        n = int(err.splitlines()[-1].split()[0])
        self.assertEqual((code, self.lines()[-1].split()[2:]), (1, ["1", str(len(rule.model(self.broken).words)), str(n)]))

    def test_default_path(self):
        env = {"RULE_LOG": "", "XDG_STATE_HOME": self.dir.name}
        run(self.file(self.keep), env=env)
        self.assertTrue(os.path.exists(os.path.join(self.dir.name, "rule-of-the-day", "log")))
        with mock.patch.dict(os.environ, {"RULE_LOG": "", "XDG_STATE_HOME": "", "HOME": self.dir.name}):
            self.assertEqual(rule.log_path(), os.path.join(self.dir.name, ".local", "state", "rule-of-the-day", "log"))

    def test_failures_exit_2_and_are_not_logged(self):
        cases = [(os.path.join(self.dir.name, "nope.txt"), "rule: error: {}: No such file or directory"),
                 (self.file("", "empty.txt"), "{}: error: no words to check"),
                 (self.file("2026, 10, 13.", "numbers.txt"), "{}: error: no words to check"),
                 (self.file(b"caf\xff", "latin1.txt"), "rule: error: {}: not valid UTF-8")]
        for path, message in cases:
            self.assertEqual(run(path, env=self.env), (2, "", message.format(path) + "\n"))
        self.assertEqual(run("-", stdin=b"\xff", env=self.env)[2], "rule: error: <stdin>: not valid UTF-8\n")
        self.assertFalse(os.path.exists(self.log))

    def test_checked_file_is_untouched(self):
        draft = self.file("We walked to the market.\r\n\tA kick!\n")
        def digest():
            with open(draft, "rb") as f:
                return hashlib.sha256(f.read()).hexdigest()
        before = digest()
        for name in ROTATION:
            run("--rule", name, draft, env=self.env)
        run(draft, env=self.env)
        self.assertEqual(digest(), before)

    def test_record(self):
        with open(self.file("", "fixture.log"), "w") as f:
            f.write("2026-10-11 no-the 1 64 3\n2026-10-11 no-the 0 66 0\n2026-10-12 no-be 1 71 5\n"
                    "2026-10-13 no-dash 0 58 0\n")
        code, out, _ = run("--record", env={"RULE_LOG": f.name})
        self.assertEqual((code, out.splitlines()), (0, [
            "2026-10-11  no-the   broke     3 of 64 words",
            "2026-10-11  no-the   survived  0 of 66 words",
            "2026-10-12  no-be    broke     5 of 71 words",
            "2026-10-13  no-dash  survived  0 of 58 words",
            "Survived 2 of 3 days on record."]))
        self.assertEqual(run("--record", env=self.env), (0, "No days on record.\n", ""))


class Help(unittest.TestCase):
    def test_help_ends_with_the_table_line(self):
        code, out, _ = run("--help")
        self.assertEqual(code, 0)
        self.assertEqual(out.splitlines()[-2:], ["", "Rules are drawn from a fixed table. A given date always gives "
                                                     "the same rule. There is no way to ignore a rule."])

    def test_argument_errors(self):
        self.assertEqual(run("--rule", "no-5", "x.txt"), (2, "", 'rule: error: unknown rule "no-5"; see rule --list\n'))
        self.assertEqual(run("--fix", "x.txt")[0], 2)
        self.assertEqual(run("--rule", "no-the")[0], 2)
        self.assertEqual(run("a.txt", "b.txt")[0], 2)


if __name__ == "__main__":
    unittest.main()
