"""Checks for corrigenda.py: parsers on histories written by real shells (fixtures/), rules in isolation.

uv run python -m unittest -v
"""

import contextlib
import io
import os
import re
import subprocess
import sys
import unittest
from datetime import datetime
from unittest import mock

import corrigenda as c

FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
# The commands the captured sessions ran, so a result does not depend on the PATH of the machine running the tests.
ON_PATH = {"git", "ls", "grep", "egrep", "uname"}
THINNING = "Counts are what this file still holds. A shell set to drop duplicates or old entries holds fewer."
ALIAS = re.compile(r"alias [A-Za-z][A-Za-z0-9_-]*='[A-Za-z][A-Za-z0-9_-]*'")


def which(word):
    return "/usr/bin/" + word if word in ON_PATH else None


def fixture(name):
    with open(os.path.join(FIXTURES, name), "rb") as f:
        return c.parse(f.read())


def rows_of(name):
    return c.find(fixture(name)[0], on_path=which)


def page_of(name, bold=False):
    entries, zsh = fixture(name)
    return c.page(os.path.join(FIXTURES, name), entries, c.find(entries, on_path=which), c.rc_file(zsh), bold=bold)


def joined(page):
    return " ".join(page.split())


def typed(*lines, gap=None):
    """Entries for a rule in isolation; gap gives every entry a time, that many seconds after the last."""
    return [c.Entry(n, None if gap is None else 1700000000 + n * gap, text) for n, text in enumerate(lines, 1)]


class Distance(unittest.TestCase):
    def test_a_swap_costs_one(self):
        self.assertEqual(c.distance("gti", "git"), 1)
        self.assertEqual(c.distance("sl", "ls"), 1)

    def test_known_distances(self):
        self.assertEqual(c.distance("kitten", "sitting"), 3)
        self.assertEqual(c.distance("gerp", "egrep"), 2)
        self.assertEqual(c.distance("ca", "abc"), 3)  # optimal string alignment, not unrestricted Damerau

    def test_limit_is_one_up_to_four_characters(self):
        self.assertEqual(c.distance("tig", "git"), 2)
        self.assertEqual(c.find(typed("tig x", "git x", "tig x", "git x"), which), [])
        self.assertEqual(c.distance("rgpe", "grep"), 2)
        self.assertEqual(c.find(typed("rgpe x", "grep x", "rgpe x", "grep x"), which), [])

    def test_limit_is_two_above_four_characters(self):
        rows = c.find(typed("gerp x", "egrep x", "gerp x", "egrep x"), which)
        self.assertEqual([(r.slip, r.fix, r.count) for r in rows], [("gerp", "egrep", 2)])
        self.assertEqual(c.distance("rgepe", "egrep"), 3)
        self.assertEqual(c.find(typed("rgepe x", "egrep x", "rgepe x", "egrep x"), which), [])


class Parse(unittest.TestCase):
    def sed_agrees(self, name):
        """For every entry, sed -n Np on the file prints a line holding the entry's first word."""
        entries, _ = fixture(name)
        self.assertTrue(entries)
        for e in entries:
            first = e.text.split()[0]
            line = subprocess.run(["sed", "-n", f"{e.line}p", os.path.join(FIXTURES, name)],
                                  capture_output=True, text=True, errors="replace", check=True).stdout
            self.assertIn(first, line, f"{name} line {e.line}")

    def test_bash_plain(self):
        entries, zsh = fixture("bash-plain.hist")
        self.assertFalse(zsh)
        self.assertEqual([e.line for e in entries], list(range(1, 10)))
        self.assertTrue(all(e.ts is None for e in entries))
        self.sed_agrees("bash-plain.hist")

    def test_bash_timestamped(self):
        entries, zsh = fixture("bash-timestamped.hist")
        self.assertFalse(zsh)
        self.assertEqual([e.line for e in entries], list(range(2, 2 * len(entries) + 1, 2)))
        self.assertTrue(all(e.ts for e in entries))
        self.sed_agrees("bash-timestamped.hist")

    def test_zsh_extended_with_a_multi_line_entry(self):
        entries, zsh = fixture("zsh-extended.hist")
        self.assertTrue(zsh)
        self.assertTrue(all(e.ts for e in entries))
        loop = [e for e in entries if "\n" in e.text]
        self.assertEqual(len(loop), 1)
        self.assertEqual(loop[0].text, "for i in 1 2; do\necho $i\ndone")
        after = entries[entries.index(loop[0]) + 1]
        self.assertEqual(after.line, loop[0].line + 3)
        with open(os.path.join(FIXTURES, "zsh-extended.hist"), "rb") as f:
            self.assertIn(b"echo 2\xc3\x83\xb73\n", f.read())  # zsh metafied the 0x97 of the sign: not UTF-8
        self.assertEqual(after.text[:6], "echo 2")
        self.sed_agrees("zsh-extended.hist")

    def test_mixed_and_garbage(self):
        entries, _ = fixture("bash-mixed.hist")
        self.assertEqual((sum(e.ts is not None for e in entries), len(entries)), (3, 8))
        entries, _ = c.parse(bytes(range(256)) * 64)  # not UTF-8: parsed, no crash
        self.assertIn("normal is dead", c.page("noise", entries, c.find(entries, which), "~/.bashrc"))
        err = io.StringIO()
        with contextlib.redirect_stderr(err):  # a binary, here the interpreter itself: one sentence, exit 2
            self.assertEqual(c.main([sys.executable]), 2)
        self.assertTrue(err.getvalue().endswith(" does not read as a shell history.\n"))


class Rules(unittest.TestCase):
    def test_changed_arguments_are_not_a_slip(self):
        self.assertEqual(c.find(typed("git add a", "git add b") * 3, which), [])
        self.assertEqual(c.find(typed("gti add a", "git add b", "gti add a", "git add b"), which), [])

    def test_a_real_command_is_not_a_slip(self):
        # gti is known here by use (typed 3 times), but git is on PATH, so git then gti is no slip
        self.assertEqual(c.find(typed(*["git x", "gti x", "pwd"] * 3), which), [])

    def test_correction_known_by_use(self):
        lines = ("mkea x", "mkae x", "mkea x", "mkae x", "mkae y")  # mkae: on no PATH, typed 3 times
        self.assertEqual([r.fix for r in c.find(typed(*lines), which)], ["mkae"])
        self.assertEqual(c.find(typed(*lines[:4]), which), [])  # typed twice is not enough

    def test_time_window(self):
        pairs = ("gti x", "git x", "gti x", "git x")
        self.assertEqual(c.find(typed(*pairs, gap=60), which)[0].count, 2)
        self.assertEqual(c.find(typed(*pairs, gap=61), which), [])

    def test_timestamped_fixture_drops_the_pair_five_minutes_apart(self):
        rows = rows_of("bash-timestamped.hist")
        self.assertEqual([(r.slip, r.fix, r.count) for r in rows], [("gti", "git", 2)])
        with open(os.path.join(FIXTURES, "bash-timestamped.hist")) as f:
            lines = f.read().split("\n")
        first = next(i for i, line in enumerate(lines) if line.startswith("gti "))
        self.assertEqual(rows[0].line, first + 1)
        self.assertEqual(c.day(rows[0].ts), datetime.fromtimestamp(int(lines[first - 1][1:])).date().isoformat())

    def test_rate_guard_drops_an_alias_in_daily_use(self):
        entries, _ = fixture("bash-alias.hist")
        words = [e.text.split()[0] for e in entries]
        self.assertEqual(words.count("ll"), 40)
        self.assertEqual(sum(1 for a, b in zip(words, words[1:]) if (a, b) == ("ll", "ls")), 2)
        self.assertNotIn("ll", [r.slip for r in rows_of("bash-alias.hist")])

    def test_only_the_dominant_correction(self):
        rows = rows_of("bash-alias.hist")
        self.assertEqual([(r.slip, r.fix, r.count) for r in rows], [("gerp", "grep", 3)])
        # A tie passes the rate guard twice over; the earlier first sighting is the one kept.
        tie = typed("gerp x", "grep x", "gerp x", "egrep x", "gerp x", "grep x", "gerp x", "egrep x")
        self.assertEqual([(r.slip, r.fix, r.count) for r in c.find(tie, which)], [("gerp", "grep", 2)])

    def test_exactly_half_stays(self):
        self.assertEqual(len(c.find(typed("gti x", "git x", "gti x", "git x", "gti", "gti"), which)), 1)
        self.assertEqual(c.find(typed("gti x", "git x", "gti x", "git x", "gti", "gti", "gti"), which), [])

    def test_retirement(self):
        self.assertEqual([(r.slip, r.fix, r.count, r.line) for r in rows_of("bash-plain.hist")], [("gti", "git", 3, 1)])
        self.assertEqual(rows_of("bash-plain-retired.hist"), [])
        self.assertIn("The edition stands as printed.", page_of("bash-plain-retired.hist"))

    def test_ranking_and_ties(self):
        rows = rows_of("zsh-extended.hist")
        self.assertEqual([(r.slip, r.fix, r.count) for r in rows], [("gti", "git", 2), ("sl", "ls", 2)])
        self.assertLess(rows[0].line, rows[1].line)


class Page(unittest.TestCase):
    def test_privacy(self):
        with open(os.path.join(FIXTURES, "bash-secret.hist")) as f:
            self.assertIn("SECRET123", f.read())
        out = page_of("bash-secret.hist") + "\n".join(c.aliases(rows_of("bash-secret.hist")))
        self.assertIn("for gti read git,", out)
        for secret in ("SECRET123", "push", "example.invalid"):
            self.assertNotIn(secret, out)

    def test_three_time_statements_and_thinning(self):
        statements = {
            "bash-plain.hist": "This history keeps no times. Corrections were taken from adjacent lines.",
            "bash-plain-retired.hist": "This history keeps no times.",
            "bash-timestamped.hist": "Every entry carries a time. A correction counts if it follows within 60 seconds.",
            "zsh-extended.hist": "Every entry carries a time. A correction counts if it follows within 60 seconds.",
            "bash-mixed.hist": "3 of 8 entries carry times. Where both had one, the correction had to follow "
                               "within 60 seconds; elsewhere adjacent lines were taken.",
        }
        for name, statement in statements.items():
            text = joined(page_of(name))
            self.assertIn(statement, text, name)
            self.assertIn(THINNING, text, name)

    def test_widest_row(self):
        row = c.Row("a" * 14, "b" * 14, 99999, 999999, 1791900000)
        line = c.ledger([row], bold=False)[0]
        self.assertEqual(len(line), 77)
        self.assertLessEqual(len(line), 79)

    def test_counts_read_down_a_column(self):
        lines = c.ledger([c.Row("gti", "git", 212, 40211, None), c.Row("sl", "ls", 3, 7, None)], bold=False)
        self.assertEqual(lines, ["line 40211: for gti read git, 212 times.",
                                 "line 7: for sl read ls,         3 times."])

    def test_head_writes_home_as_tilde(self):
        with mock.patch.dict(os.environ, {"HOME": os.path.dirname(FIXTURES)}):
            self.assertIn("to the shell history at ~/fixtures/bash-plain.hist, 9 entries.", page_of("bash-plain.hist"))

    def test_a_long_path_breaks_after_a_slash(self):
        head = "to the shell history at ~/hundred/047-corrigenda/fixtures/zsh-extended.hist, 13 entries."
        self.assertEqual(c.wrap(head, 46), ["to the shell history at", "~/hundred/047-corrigenda/fixtures/",
                                            "zsh-extended.hist, 13 entries."])
        self.assertEqual(c.wrap(head, 72), ["to the shell history at",
                                            "~/hundred/047-corrigenda/fixtures/zsh-extended.hist, 13 entries."])
        head = "to the shell history at ~/.bash_history, 500\u00a0entries."
        self.assertEqual(c.wrap(head, 46), ["to the shell history at ~/.bash_history,", "500 entries."])

    def test_alias_block_is_last_and_pure(self):
        for name in ("bash-plain.hist", "zsh-extended.hist", "bash-alias.hist"):
            block = c.aliases(rows_of(name))
            self.assertTrue(block and all(ALIAS.fullmatch(line) for line in block), name)
            self.assertEqual(page_of(name, bold=True).rstrip("\n").split("\n")[-len(block):], block, name)
            self.assertNotIn("\x1b", "\n".join(block))

    def test_rc_heading(self):
        self.assertIn("Errata slip, to be tipped in at ~/.zshrc", page_of("zsh-extended.hist"))
        with mock.patch.dict(os.environ, {"SHELL": "/bin/bash"}):
            self.assertIn("Errata slip, to be tipped in at ~/.bashrc", page_of("bash-plain.hist"))

    def test_only_the_count_is_bold(self):
        text = page_of("zsh-extended.hist", bold=True)
        self.assertEqual(re.findall(r"\x1b\[[0-9;]*m", text), ["\x1b[1m", "\x1b[0m"] * 2)
        self.assertEqual(re.findall(r"\x1b\[1m(.*?)\x1b\[0m", text), ["2", "2"])
        self.assertNotIn("\x1b", page_of("zsh-extended.hist", bold=False))


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