"""Checks for itemised: pure functions, then real runs in throwaway directories.

Run from this folder: uv run python -m unittest -q
"""

import contextlib
import io
import os
import signal
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path

import itemised as it

SCRIPT = str(Path(__file__).resolve().parent / "itemised.py")


def receipt(items: dict[str, dict[str, int]], **kw) -> list[str]:
    run = it.Run(
        argv=["true"], when="2026-10-13 14:02:07", cwd="~/t", items=items, **kw
    )
    return it.render(run)


def kinds(created=None, changed=None, removed=None) -> dict[str, dict[str, int]]:
    return {
        "created": created or {},
        "changed": changed or {},
        "removed": removed or {},
    }


def cli(args: list[str], cwd: str, **kw) -> subprocess.CompletedProcess:
    return subprocess.run(
        [sys.executable, SCRIPT, *args],
        check=False,
        cwd=cwd,
        capture_output=True,
        text=True,
        **kw,
    )


class Columns(unittest.TestCase):
    def test_width(self):
        self.assertEqual(it.width("abc"), 3)
        self.assertEqual(it.width("漢字"), 4)  # W
        self.assertEqual(it.width("Ａ"), 2)  # F, fullwidth A
        self.assertEqual(it.width("é"), 1)  # combining acute counts 0

    def test_shown(self):
        self.assertEqual(it.shown(os.fsdecode(b"a\xffb")), "a\\xffb")
        self.assertEqual(it.shown("a\x1bb\nc"), "a\\x1bb\\x0ac")
        self.assertEqual(it.shown("a\\b"), "a\\\\b")
        self.assertEqual(it.shown("\x7f\x85"), "\\x7f\\x85")
        self.assertEqual(it.shown("plain 漢.txt"), "plain 漢.txt")

    def test_wide_character_moves_whole(self):
        rows = it.hard("a" * 47 + "漢" + "b")
        self.assertEqual(rows, ["a" * 47, "漢b"])

    def test_long_path_wraps_and_joins_back(self):
        path = "/".join(["d" * 23] * 5)  # 119 characters
        path += "x"
        self.assertEqual(len(path), 120)
        rows = it.lr(path, "+0 B")
        self.assertTrue(all(it.width(r) <= it.W for r in rows))
        self.assertTrue(rows[-1].endswith("+0 B"))
        joined = "".join(rows[:-1]) + rows[-1].removesuffix("+0 B").rstrip()
        self.assertEqual(joined, path)


class Diff(unittest.TestCase):
    def test_kinds(self):
        before = {
            "same": (5, 1, 1, 0o100644),
            "grow": (5, 1, 1, 0o100644),
            "touch": (5, 1, 1, 0o100644),
            "gone": (7, 1, 1, 0o100644),
        }
        after = {
            "same": (5, 1, 1, 0o100644),
            "grow": (9, 2, 2, 0o100644),
            "touch": (5, 1, 2, 0o100644),
            "new": (3, 2, 2, 0o100644),
        }
        d = it.diff(before, after)
        self.assertEqual(d["created"], {"new": 3})
        self.assertEqual(d["changed"], {"grow": 4, "touch": 0})
        self.assertEqual(d["removed"], {"gone": -7})

    def test_ctime_only_on_real_file(self):
        with tempfile.TemporaryDirectory() as tmp:
            f = Path(tmp, "f.txt")
            f.write_bytes(b"0123456789")
            st = f.stat()
            before = it.snapshot([(tmp, "")], it.LIMIT).files
            time.sleep(0.05)
            f.write_bytes(b"9876543210")  # same size
            os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns))  # same mtime
            after = it.snapshot([(tmp, "")], it.LIMIT).files
            self.assertEqual(before["f.txt"][:2], after["f.txt"][:2])
            self.assertEqual(it.diff(before, after)["changed"], {"f.txt": 0})


class Grouping(unittest.TestCase):
    def test_twenty_versus_twenty_one(self):
        twenty = {f"d/{i:02}": 1 for i in range(20)}
        self.assertEqual(len(it.group(twenty, [""])), 20)
        twenty_one = {f"d/{i:02}": 1 for i in range(21)}
        self.assertEqual(it.group(twenty_one, [""]), [("d/", 21, 21)])

    def test_outermost_wins(self):
        items = {f"a/b/c/{i:02}": 2 for i in range(30)}
        items["a/top"] = 5
        self.assertEqual(it.group(items, [""]), [("a/", 31, 65)])

    def test_root_is_never_grouped_and_full_lists_all(self):
        items = {f"f{i:02}": 1 for i in range(30)}
        self.assertEqual(len(it.group(items, [""])), 30)
        nested = {f"d/{i:02}": 1 for i in range(30)}
        self.assertEqual(len(it.group(nested, [""], full=True)), 30)

    def test_other_root_is_never_grouped(self):
        items = {f"~/x/f{i:02}": 1 for i in range(30)}
        self.assertEqual(len(it.group(items, ["~/x/", ""])), 30)

    def test_the_example_in_the_card(self):
        sizes = {f"dist/assets/chunk-{i:02}.js": 50_000 for i in range(31)}
        sizes["dist/index.js"] = 1_615_230 - 31 * 50_000
        self.assertEqual(sum(sizes.values()), 1_615_230)
        rows = receipt(kinds(created=sizes))
        line = "dist/ x 32" + " " * 31 + "+1.6 MB"
        self.assertIn(line, rows)
        self.assertEqual(it.width(line), 48)
        self.assertFalse(
            [r for r in rows if "dist/index.js" in r or "dist/assets/" in r]
        )
        self.assertIn("created     32 files" + " " * 16 + "+1,615,230 B", rows)


class Receipt(unittest.TestCase):
    def test_last_line_follows_the_net(self):
        self.assertEqual(
            receipt(kinds(created={"a": 3000}))[-2:],
            [it.RULE, "Amount due" + " " * 32 + "3.0 kB"],
        )
        self.assertEqual(
            receipt(kinds(removed={"a": -4000}, created={"b": 6}))[-1],
            "Change due" + " " * 32 + "4.0 kB",
        )
        self.assertEqual(
            receipt(kinds(created={"a": 5}, removed={"b": -5}))[-1], "Nothing due."
        )
        empty = receipt(kinds())
        self.assertIn("No items.", empty)
        self.assertEqual(empty[-1], "Nothing due.")

    def test_number_is_stable(self):
        a = kinds(created={"x": 1, "y": 2}, changed={"z": -3}, removed={"w": -4})
        b = kinds(removed={"w": -4}, changed={"z": -3}, created={"y": 2, "x": 1})
        self.assertEqual(it.number(a), it.number(b))
        self.assertNotEqual(it.number(a), it.number(kinds(created={"x": 1, "y": 3})))
        self.assertEqual(it.number(kinds()), "00000000")

    def test_every_row_fits(self):
        long = "deep/" * 30 + "file.txt"
        cjk = "漢字" * 20 + ".txt"
        items = kinds(
            created={
                long: 10,
                cjk: 0,
                "été.txt": 1,
                **{f"node_modules/p/{i}": 7 for i in range(1204)},
            },
            changed={"tsconfig.tsbuildinfo": 3100},
            removed={"a\\x1b[31mb\\x0ac": -1},
        )
        rows = receipt(
            items,
            also=["~/" + "x" * 60],
            skipped={f"{i}/.git/" for i in range(8)},
            dropped={"vendor/"},
            unreadable={"locked/", "other/"},
            free=(12_400_000_000, 12_300_000_000),
            elsewhere=["/mnt/x/"],
        )
        self.assertTrue(all(it.width(r) <= it.W for r in rows), rows)
        self.assertIn("node_modules/ x 1,204" + " " * 20 + "+8.4 kB", rows)
        self.assertIn("Not examined: outside the paths listed above", rows)
        self.assertTrue(
            any(r.startswith("Not itemised: 100.0 MB more used") for r in rows)
        )
        painted = it.paint(rows, colour=True).splitlines()
        self.assertEqual(len(painted), len(rows) + 2)
        for line in painted:
            bare = line.replace(it.PAPER, "").replace(it.RESET, "")
            self.assertEqual(it.width(bare), it.W)
        self.assertNotIn("\x1b", it.paint(rows, colour=False))


class Runs(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.dir = self.tmp.name

    def tearDown(self):
        self.tmp.cleanup()

    def test_created_changed_removed(self):
        for name, size in (("keep.txt", 10), ("edit.txt", 100), ("old.bin", 5000)):
            Path(self.dir, name).write_bytes(b"x" * size)
        script = "head -c 1000 /dev/zero > new.bin; echo hello >> edit.txt; rm old.bin"
        p = cli(["sh", "-c", script], self.dir)
        lines = p.stderr.splitlines()
        self.assertEqual(p.returncode, 0)
        for row in (
            "new.bin".ljust(41) + "+1.0 kB",
            "edit.txt".ljust(44) + "+6 B",
            "old.bin".ljust(41) + "-5.0 kB",
            "net".ljust(40) + "-3,994 B",
        ):
            self.assertIn(row, lines)
        self.assertFalse([r for r in lines if "keep.txt" in r])
        self.assertEqual(lines[-2:], [it.RULE, "Change due" + " " * 32 + "4.0 kB"])

    def test_command_is_untouched(self):
        p = cli(["sh", "-c", "echo hi; echo err >&2; exit 3"], self.dir)
        self.assertEqual((p.stdout, p.returncode), ("hi\n", 3))
        self.assertTrue(p.stderr.startswith("err\n"))
        self.assertEqual(p.stderr.splitlines()[-1], "Nothing due.")
        missing = cli(["nosuchprogram"], self.dir)
        self.assertEqual(missing.returncode, 127)
        self.assertEqual(missing.stderr, "itemised: not found: nosuchprogram\n")
        nothing = cli([], self.dir)
        self.assertEqual(nothing.returncode, 2)
        self.assertTrue(nothing.stderr.startswith("itemised: nothing to run."))

    def test_main_leaves_signals_alone(self):
        probe = (
            "import signal; open('disposition.txt', 'w').write("
            "f'{signal.getsignal(signal.SIGINT)} {signal.getsignal(signal.SIGQUIT)}')"
        )
        sigs = (signal.SIGINT, signal.SIGQUIT)
        before = {s: signal.getsignal(s) for s in sigs}
        cwd = os.getcwd()
        os.chdir(self.dir)
        try:
            with contextlib.redirect_stderr(io.StringIO()) as err:
                code = it.main([sys.executable, "-c", probe])
        finally:
            os.chdir(cwd)
        self.assertEqual(code, 0)
        self.assertIn("disposition.txt", err.getvalue())
        seen = Path(self.dir, "disposition.txt").read_text()
        self.assertNotIn("SIG_IGN", seen)
        self.assertEqual({s: signal.getsignal(s) for s in sigs}, before)

    def test_ctrl_c_ends_the_child_and_still_prints(self):
        p = subprocess.Popen(
            [sys.executable, SCRIPT, "sleep", "30"],
            cwd=self.dir,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            start_new_session=True,
        )
        deadline = time.monotonic() + 10
        while not subprocess.run(
            ["pgrep", "-P", str(p.pid), "-x", "sleep"], check=False, capture_output=True
        ).stdout:
            self.assertLess(time.monotonic(), deadline, "sleep never started")
            time.sleep(0.05)
        started = time.monotonic()
        os.killpg(p.pid, signal.SIGINT)  # what the terminal does on Ctrl-C
        _, err = p.communicate(timeout=10)
        self.assertLess(time.monotonic() - started, 5)
        self.assertEqual(p.returncode, 130)
        self.assertEqual(err.splitlines()[-1], "Nothing due.")
        self.assertIn("exit 130", err)


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