"""The smallest checks that fail if the register's logic breaks. Fixture strings only; no real file is written."""

import io
import re
import unittest
from contextlib import redirect_stderr, redirect_stdout
from datetime import date
from unittest import mock

import firsts

TODAY = date(2026, 4, 2)
CELL = re.compile(r"^[ \[]([A-Z][a-z]{2} [ 0-9][0-9]| {0,5}[0-9]{1,3})[ \]][ *]$")


def book(text):
    return firsts.parse(text)


def cells(table, years):
    """Split each table row into its label and nine-character cells, using the header for the label width."""
    lines = table.split("\n")
    header = lines[0]
    pad = len(header) - len(header.lstrip(" ")) - 1
    rows = []
    for line in lines[1:]:
        if not line:
            break
        full = line.ljust(pad + 9 * years)
        rows.append((full[:pad], [full[pad + 9 * i:pad + 9 * (i + 1)] for i in range(years)]))
    return pad, rows


class Today(unittest.TestCase):
    def setUp(self):
        patcher = mock.patch.object(firsts, "today", return_value=TODAY)
        patcher.start()
        self.addCleanup(patcher.stop)


class Names(unittest.TestCase):
    def test_normalise(self):
        for typed in ("First Frost.", "first  frost", "frost"):
            self.assertEqual(firsts.normalise(typed), "frost")

    def test_fold(self):
        self.assertEqual(firsts.fold("swallows"), firsts.fold("swallow"))

    def test_command_name(self):
        self.assertEqual(firsts.command_name("firsts.py"), "uv run firsts.py")
        self.assertEqual(firsts.command_name("/some/dir/firsts"), "firsts")

    def test_doy(self):
        self.assertEqual(firsts.doy(date(2024, 3, 1)), 61)
        self.assertEqual(firsts.doy(date(2025, 3, 1)), 60)


class Parse(unittest.TestCase):
    TEXT = (
        "# First occurrences. One line per entry. A line is never changed.\n"
        "# Opened 2026-03-11.\n"
        "\n"
        "2026-03-11 | seen | swallow | over the mill pond\n"
        "2025-04-02 | recalled | swallow | about the second week | I think\n"
        "erratum | 2026 | swallow | filed 2026-04-02 | the 11th was a house martin | not a swallow\n"
        "a line someone typed\n"
        "2026-03-20 | seen | swallows\n"
    )

    def test_parse(self):
        b = book(self.TEXT)
        self.assertEqual(b.opened, date(2026, 3, 11))
        self.assertEqual([(e.date, e.basis, e.event) for e in b.entries],
                         [(date(2026, 3, 11), "seen", "swallow"), (date(2025, 4, 2), "recalled", "swallow")])
        self.assertEqual(b.entries[1].note, "about the second week | I think")
        self.assertEqual(b.errata[0].text, "the 11th was a house martin | not a swallow")
        self.assertEqual(b.errata[0].filed, date(2026, 4, 2))
        self.assertEqual(b.problems, [(7, "is not an entry. Left as it is."),
                                      (8, "repeats swallow 2026. The first line stands.")])


class Refusals(Today):
    def test_future_and_repeat(self):
        held = book("2026-03-11 | seen | swallow\n").entries
        new = [firsts.Entry(date(2027, 4, 11), "seen", "frost", "", 1),
               firsts.Entry(date(2026, 3, 30), "seen", "swallows", "", 2),
               firsts.Entry(date(2025, 3, 30), "recalled", "frost", "", 3)]
        found = firsts.refusals(held, new)
        self.assertEqual([(i, m) for i, m, _ in found],
                         [(0, "11 Apr 2027 has not happened."),
                          (1, "swallow, 2026: already entered, 11 Mar. The first is final.")])

    def test_repeat_inside_a_paste(self):
        new = [firsts.Entry(date(2025, 3, 30), "recalled", "frost", "", 1),
               firsts.Entry(date(2025, 4, 1), "recalled", "frost", "", 2)]
        self.assertEqual(len(firsts.refusals([], new)), 1)


class SplitErratum(unittest.TestCase):
    def test_split(self):
        words = "wood anemone 2025 it was a wood sorrel".split()
        self.assertEqual(firsts.split_erratum(words), ("wood anemone", 2025, "it was a wood sorrel"))

    def test_usage(self):
        usage = "Usage: firsts erratum EVENT... YEAR TEXT..."
        self.assertEqual(firsts.split_erratum("wood anemone it was".split()), usage)
        self.assertEqual(firsts.split_erratum("wood anemone 2025".split()), usage)
        self.assertEqual(firsts.split_erratum("2025 text".split()), usage)


class Table(Today):
    def test_cells_are_nine_characters(self):
        b = book("2023-01-05 | seen | x\n2024-02-10 | recalled | x\n2025-11-02 | seen | x\n"
                 "erratum | 2025 | x | filed 2026-01-01 | wrong\n")
        for days in (False, True):
            table = firsts.render_table(b, days=days)
            _, rows = cells(table, 3)
            self.assertEqual(len(rows), 1)
            for cell in rows[0][1]:
                self.assertEqual(len(cell), 9)
                self.assertRegex(cell, CELL)
            if days:
                self.assertEqual([c.strip(" []*") for c in rows[0][1]], ["5", "41", "306"])
        self.assertEqual(cells(firsts.render_table(b), 3)[1][0][1], [" Jan  5  ", "[Feb 10] ", " Nov  2 *"])

    def test_label_width(self):
        long = "a" * 30
        b = book(f"2025-04-02 | seen | {long}\n2025-03-01 | seen | frost\n")
        table = firsts.render_table(b)
        pad, rows = cells(table, 1)
        self.assertEqual(pad, 24)
        self.assertIn("a" * 21 + "~", table)
        self.assertNotIn("a" * 22, table.split("\n\n")[0])
        pad, _ = cells(firsts.render_table(book("2025-03-01 | seen | frost\n")), 1)
        self.assertEqual(pad, len("frost") + 2)

    def test_width_rule(self):
        text = ("2022-05-01 | seen | cuckoo\n"
                "2023-04-10 | recalled | swallow\n2024-03-29 | recalled | swallow\n"
                "2025-04-02 | recalled | swallow\n2026-03-11 | seen | swallow\n")
        table = firsts.render_table(book(text), width=40)
        header = table.split("\n")[0]
        self.assertNotIn("2022", header)
        self.assertNotIn("cuckoo", table.split("\n\n")[0])
        self.assertTrue(all(len(line) <= 40 for line in table.split("\n\n")[0].split("\n")))
        self.assertIn("Years before 2024 not shown. firsts table --from 2022.", table)
        wide = firsts.render_table(book(text), from_year=2022, width=40)
        self.assertIn("2022", wide.split("\n")[0])
        self.assertIn("cuckoo", wide)
        self.assertNotIn("not shown", wide)

    def test_key_and_erratum(self):
        seen = firsts.render_table(book("2026-03-11 | seen | swallow\n"))
        self.assertNotIn("recalled", seen)
        self.assertNotIn("erratum", seen)
        b = book("2026-03-11 | seen | swallow\nerratum | 2026 | swallow | filed 2026-04-02 | the 14th\n")
        table = firsts.render_table(b)
        self.assertIn("swallow   Mar 11 *", table)
        self.assertIn("\n* erratum\n", table)
        self.assertNotIn("[ ]", table)
        self.assertIn("* swallow 2026, filed 2 Apr: the 14th", table)

    def test_not_yet(self):
        b = book("2025-11-02 | recalled | frost\n2025-04-02 | recalled | swallows\n2026-03-11 | seen | swallow\n")
        self.assertIn("Not yet in 2026: frost.\n", firsts.render_table(b))


class Colophon(unittest.TestCase):
    def test_counts(self):
        b = book("# Opened 2026-03-11.\n2026-03-11 | seen | swallow\n2025-04-02 | recalled | swallow\n"
                 "erratum | 2026 | swallow | filed 2026-04-02 | x\n")
        self.assertEqual(firsts.colophon(b),
                         "Book opened 11 Mar 2026. 2 entries, 1 of them older than the book. This tool has changed no line.")
        one = book("# Opened 2026-03-11.\n2026-03-11 | seen | swallow\n")
        self.assertIn("1 entry, 0 of them", firsts.colophon(one))
        bare = book("2026-03-11 | seen | swallow\n2025-04-02 | recalled | swallow\n")
        self.assertEqual(firsts.colophon(bare), "2 entries. This tool has changed no line.")


class Recorder:
    """Stands in for open(): reads from a fixture string, records every append."""

    def __init__(self, content):
        self.content, self.appends = content, []

    def __call__(self, path, mode="r", **kwargs):
        self.test_mode(mode)
        if mode == "r":
            if self.content is None:
                raise FileNotFoundError(path)
            return io.StringIO(self.content)
        recorder = self

        class Sink(io.StringIO):
            def close(self):
                recorder.appends.append(self.getvalue())
                super().close()
        return Sink()

    @staticmethod
    def test_mode(mode):
        if mode not in ("r", "a"):
            raise AssertionError(f"open with mode {mode}")


class FirstWrite(Today):
    def add(self, content):
        recorder = Recorder(content)
        with mock.patch.object(firsts, "open", recorder, create=True), \
                mock.patch.dict("os.environ", {"FIRSTS_FILE": "book.txt"}), \
                redirect_stdout(io.StringIO()) as out, redirect_stderr(io.StringIO()):
            status = firsts.main(["add", "first", "swallow"])
        return status, recorder.appends, out.getvalue()

    def test_missing_and_empty_file_get_the_header(self):
        expected = ("# First occurrences. One line per entry. A line is never changed.\n"
                    "# Opened 2026-04-02.\n2026-04-02 | seen | swallow\n")
        for content in (None, ""):
            status, appends, out = self.add(content)
            self.assertEqual(status, 0)
            self.assertEqual(appends, [expected])
            self.assertTrue(out.startswith("Entered. swallow, 2 Apr 2026, seen. Day 92.\n"))

    def test_file_with_bytes_gets_the_entry_only(self):
        _, appends, _ = self.add("2025-04-02 | recalled | frost\n")
        self.assertEqual(appends, ["2026-04-02 | seen | swallow\n"])
        _, appends, _ = self.add("2025-04-02 | recalled | frost")
        self.assertEqual(appends, ["\n2026-04-02 | seen | swallow\n"])

    def test_comparison_lines(self):
        _, _, out = self.add("2025-04-02 | recalled | swallow\n2024-04-02 | seen | swallow\n2023-04-12 | seen | swallow\n")
        self.assertIn("2025: [2 Apr] (day 92). This entry is on the same day.\n"
                      "2024: 2 Apr (day 93). This entry is 1 day earlier.\n"
                      "2023: 12 Apr (day 102). This entry is 10 days earlier.\n", out)


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