"""Tests for best_before.py. Every case runs in its own temp folder; none
calls `run` in the project folder (the project's own `tests` check runs
this suite, so acceptance check 1 is a shell check outside it)."""

import ast
import datetime
import json
import os
import pty
import re
import shutil
import subprocess
import sys
import tempfile
import time
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
TOOL = os.path.join(ROOT, "best_before.py")
sys.path.insert(0, ROOT)
import best_before  # noqa: E402

HAS_GIT = shutil.which("git") is not None
HEX12 = re.compile(r"[0-9a-f]{12}")


def slurp(path, mode="r"):
    with open(path, mode, **({} if "b" in mode else {"encoding": "utf-8"})) as f:
        return f.read()


def iso(epoch):
    return datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).isoformat()


class Folder(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.mkdtemp(prefix="bb-")
        self.addCleanup(shutil.rmtree, self.dir, True)

    def write(self, name, text):
        path = os.path.join(self.dir, name)
        with open(path, "w") as f:
            f.write(text)

    def task(self, *checks, goal=None):
        text = f'goal = "{goal}"\n' if goal else ""
        for c in checks:
            text += "\n[[check]]\n" + "".join(f"{k} = {json.dumps(v)}\n" for k, v in c.items())
        self.write("best-before.toml", text)

    def bb(self, *args, env=None):
        r = subprocess.run([sys.executable, TOOL, *args], cwd=self.dir, capture_output=True,
                           env=env or {k: v for k, v in os.environ.items() if k != "NO_COLOR"})
        out = r.stdout.decode("utf-8")
        # Output hygiene (acceptance 9) on every captured output.
        self.assertNotIn(b"\x1b", r.stdout)
        for line in out.splitlines():
            if not ("run" in args and line.startswith("    ")):
                self.assertLessEqual(len(line), 72, line)
        return r.returncode, out, r.stderr.decode("utf-8")

    def ledger(self):
        with open(os.path.join(self.dir, ".best-before", "ledger.jsonl")) as f:
            return [json.loads(line) for line in f]

    def at(self, i=-1, check=None):
        rows = [e for e in self.ledger() if check is None or e["check"] == check]
        d = datetime.datetime.strptime(rows[i]["at"], "%Y-%m-%dT%H:%M:%SZ")
        return int(d.replace(tzinfo=datetime.timezone.utc).timestamp())

    def git_init(self):
        if not HAS_GIT:
            self.skipTest("git is not installed")
        subprocess.run(["git", "init", "-q"], cwd=self.dir, check=True)

    def block(self, out, name):
        lines = out.splitlines()
        i = lines.index(name)
        j = i + 1
        while j < len(lines) and lines[j].startswith(" "):
            j += 1
        return lines[i + 1:j]


class Maths(unittest.TestCase):
    def worked(self, outcomes):
        history = [{"green": g} for g in outcomes]
        num, den, flips = best_before.earned(history, 86400)
        return best_before.duration_text(num // den), flips

    def test_worked_numbers_from_the_card(self):
        self.assertEqual(self.worked([True]), ("12 h", 0))
        self.assertEqual(self.worked([True] * 10), ("21 h 49 min", 0))
        self.assertEqual(self.worked([True, False, True, False, True]), ("4 h", 4))
        self.assertEqual(self.worked([True, False] * 5), ("2 h 10 min", 9))

    def test_text_rules(self):
        self.assertEqual(best_before.age_text(59), "just now")
        self.assertEqual(best_before.age_text(3599), "59 min ago")
        self.assertEqual(best_before.age_text(48 * 3600 - 1), "47 h ago")
        self.assertEqual(best_before.age_text(48 * 3600), "2 d ago")
        self.assertEqual(best_before.duration_text(59), "59 s")
        self.assertEqual(best_before.duration_text(3600), "1 h")
        self.assertEqual(best_before.plural(1, "flip"), "1 flip")


class EndToEnd(Folder):
    def test_edit_staleness_and_lot(self):
        self.git_init()
        self.write("a.txt", "a\n")
        self.task({"name": "one", "run": "true"}, {"name": "two", "run": "true", "watch": ["a.txt"]})
        code, out, _ = self.bb("run")
        self.assertEqual(code, 0, out)
        lot = re.search(r"^Lot     ([0-9a-f]{12})$", out, re.M).group(1)
        self.assertEqual(self.bb("lot")[1].strip(), lot)
        with open(os.path.join(self.dir, "a.txt"), "a") as f:
            f.write("b\n")
        code, out, _ = self.bb()
        self.assertEqual(code, 1)
        self.assertEqual(out.splitlines()[0], "NO CERTIFICATE")
        for name in ("one", "two"):
            self.assertIn("      Files changed since.", self.block(out, name))
        new = self.bb("lot")[1].strip()
        self.assertTrue(HEX12.fullmatch(new))
        self.assertNotEqual(new, lot)
        code, out, _ = self.bb("run")
        self.assertEqual(code, 0)
        self.assertIn(f"Lot     {new}", out)
        with open(os.path.join(self.dir, "best-before.toml"), "a") as f:
            f.write('\n[[check]]\nname = "three"\nrun = "true"\nwatch = []\n')
        code, out, _ = self.bb()
        self.assertEqual(self.block(out, "one")[0][:9], "  passed ")
        self.assertEqual(self.block(out, "two")[0][:9], "  passed ")
        self.assertEqual(self.block(out, "three"), ["  never run"])

    def test_age_boundary(self):
        self.task({"name": "only", "run": "true"})
        self.assertEqual(self.bb("run")[0], 0)
        at = self.at()
        self.assertEqual(self.bb("--at", iso(at + 11 * 3600 + 59 * 60))[0], 0)
        code, out, _ = self.bb("--at", iso(at + 12 * 3600))
        self.assertEqual(code, 1)
        self.assertIn("  STALE, passed 12 h ago, was best before ", out)
        self.assertIn("      Older than the 12 h it earned.", out)
        expires = at // 60 * 60 + 12 * 3600  # floored to the minute; stale at, not after
        self.assertEqual(self.bb("--at", iso(expires - 1))[0], 0)
        self.assertEqual(self.bb("--at", iso(expires))[0], 1)
        code, out, _ = self.bb("--at", iso(at - 60))
        self.assertEqual(code, 1)
        self.assertEqual(self.block(out, "only"), ["  never run"])

    def test_earned_date_and_last_failed(self):
        self.task({"name": "flip", "run": "test ! -f flag"}, {"name": "ok", "run": "true"})
        flag = os.path.join(self.dir, "flag")
        for i in range(5):
            if i % 2:
                open(flag, "w").close()
            elif os.path.exists(flag):
                os.remove(flag)
            self.bb("run", "flip")
        for _ in range(10):
            self.bb("run", "ok")
        out = self.bb()[1]
        self.assertIn("  5 runs, 4 flips, earned 4 h, watches nothing (clock only)", self.block(out, "flip"))
        self.assertIn("  10 runs, 0 flips, earned 21 h 49 min, watches nothing (clock only)", self.block(out, "ok"))
        code, out, _ = self.bb("run", "ok")
        self.assertEqual(code, 0)
        self.assertIn("  10 runs, 0 flips, earned 21 h 49 min", "\n".join(self.block(out, "ok")))
        red = self.at(-2, "flip")
        hm = datetime.datetime.fromtimestamp(red).strftime("%H:%M")
        self.assertRegex(self.block(out, "flip")[-1], rf"^  last failed {hm} (today|yesterday)$")
        self.assertFalse(any("last failed" in line for line in self.block(out, "ok")))
        fifth = self.at(-1, "flip")
        self.assertEqual(self.bb("--at", iso(fifth + 3 * 3600 + 59 * 60))[0], 0)
        self.assertEqual(self.bb("--at", iso(fifth + 4 * 3600))[0], 1)

    def test_failure_keeps_output_and_refuses(self):
        self.task({"name": "boom", "run": "sh -c 'echo boom; exit 3'"}, {"name": "fine", "run": "true"})
        code, out, _ = self.bb("run")
        self.assertEqual(code, 1)
        self.assertIn("boom  FAILED  exit 3", out)
        self.assertIn("\n    boom\n", out)
        code, out, _ = self.bb()
        self.assertEqual(code, 1)
        self.assertIn("  FAILED, exit 3, just now", out)
        self.assertIn("  passed just now, best before ", "\n".join(self.block(out, "fine")))
        self.assertNotIn("CERTIFICATE OF COMPLETION", out)

    def test_timeout_kills_the_group(self):
        self.task({"name": "slow", "run": "sleep 30", "timeout": "1s"})
        start = time.monotonic()
        code, out, _ = self.bb("run")
        self.assertLess(time.monotonic() - start, 5)
        self.assertEqual(code, 1)
        self.assertIn("slow  FAILED  timed out after 1 s", out)
        self.assertIn('"exit":null,"timeout":true',
                      slurp(os.path.join(self.dir, ".best-before", "ledger.jsonl")))
        if shutil.which("pgrep"):
            left = subprocess.run(["pgrep", "-f", "sleep 30"], capture_output=True)
            self.assertEqual(left.stdout, b"")
        self.assertIn("  FAILED, timed out after 1 s, just now", self.bb()[1])

    def test_self_edit_guard(self):
        self.git_init()
        self.write("a.txt", "a\n")
        self.task({"name": "grow", "run": "echo x >> a.txt"})
        code, out, _ = self.bb("run")
        self.assertEqual(code, 1)
        block = self.block(out, "grow")
        self.assertTrue(block[0].startswith("  STALE, "))
        self.assertIn("      The command changed the files it was checked against.", block)
        self.assertIn("      Narrow the watch list or ignore its output.", block)
        self.assertTrue(self.ledger()[-1]["self_edit"])
        self.task({"name": "grow", "run": "echo x >> a.txt", "watch": []})
        code, out, _ = self.bb("run")
        self.assertEqual(code, 0)
        self.assertEqual(out.splitlines()[3], "CERTIFICATE OF COMPLETION")

    def test_age_only_statement(self):
        self.write("notes.txt", "x\n")
        self.task({"name": "only", "run": "true"})
        self.bb("run")
        self.write("notes.txt", "y\n")
        code, out, _ = self.bb()
        self.assertEqual(code, 0)
        lines = out.splitlines()
        self.assertTrue(lines[1].startswith("Check passed just now. Best before "))
        self.assertEqual(lines[2], "Nothing here watches the files, so this goes by the clock alone.")
        self.assertIn("watches nothing (clock only)", out)

    def test_changed_command_and_unreadable_ledger_line(self):
        self.task({"name": "c", "run": "true"})
        self.bb("run")
        with open(os.path.join(self.dir, ".best-before", "ledger.jsonl"), "a") as f:
            f.write("{not json\n")
        self.task({"name": "c", "run": "true && true"})
        code, out, err = self.bb()
        self.assertEqual(code, 1)
        self.assertEqual(self.block(out, "c"),
                         ["  never run", "      The command in the task file has changed since the last run."])
        self.assertEqual(err, "best-before: ledger line 2 unreadable, ignored\n")


class Strictness(Folder):
    GOOD = {"name": "ok", "run": "true"}

    def test_every_refusal_exits_2_and_writes_nothing(self):
        os.mkdir(os.path.join(self.dir, "sub"))
        self.task(self.GOOD)
        self.bb("run")
        ledger = os.path.join(self.dir, ".best-before", "ledger.jsonl")
        before = slurp(ledger, "rb")
        bad_files = {
            "unknown key": 'colour = "red"\n[[check]]\nname = "ok"\nrun = "true"\n',
            "typo in a check": '[[check]]\nname = "ok"\nrun = "true"\nwach = ["sub"]\n',
            "duplicate": '[[check]]\nname = "a"\nrun = "true"\n[[check]]\nname = "a"\nrun = "true"\n',
            "bad name": '[[check]]\nname = "a b/c"\nrun = "true"\n',
            "empty run": '[[check]]\nname = "a"\nrun = " "\n',
            "zero checks": 'goal = "nothing"\n',
            "missing watch": '[[check]]\nname = "a"\nrun = "true"\nwatch = ["nope"]\n',
            "escaping watch": '[[check]]\nname = "a"\nrun = "true"\nwatch = ["../x"]\n',
            "absolute watch": '[[check]]\nname = "a"\nrun = "true"\nwatch = ["/etc"]\n',
            "short max_age": '[[check]]\nname = "a"\nrun = "true"\nmax_age = "30s"\n',
            "long timeout": '[[check]]\nname = "a"\nrun = "true"\ntimeout = "2h"\n',
        }
        for why, text in bad_files.items():
            with self.subTest(why):
                self.write("best-before.toml", text)
                code, out, err = self.bb("run")
                self.assertEqual(code, 2)
                self.assertTrue(err.startswith("best-before: "), err)
                self.assertEqual(slurp(ledger, "rb"), before)
                if why == "zero checks":
                    self.assertIn("Nothing to certify. A certificate for nothing is not issued.", err)
        self.task(self.GOOD)
        for args in (["frobnicate"], ["run", "nosuchcheck"], ["run", "--at", "2026-10-14T09:30"],
                     ["lot", "--at", "2026-10-14T09:30"], ["--force"], ["--at", "soon"]):
            with self.subTest(args=args):
                code, out, err = self.bb(*args)
                self.assertEqual(code, 2)
                self.assertTrue(err.startswith("best-before: "), err)
                self.assertEqual(slurp(ledger, "rb"), before)

    def test_no_override_anywhere_in_the_source(self):
        src = slurp(TOOL)
        self.assertIsNone(re.search(r"--(force|skip|ignore|override|no-)", src))
        options = re.findall(r'add_argument\(([^)]*)\)', src)
        for opt in options:
            self.assertIsNone(re.search(r"force|skip|ignore|override", opt))


class Output(Folder):
    def test_limits_tail_and_status_silence(self):
        a, b, c = "a" * 40, "b" * 40, "c" * 40
        self.task({"name": a, "run": "for i in $(seq 1 25); do echo line $i; done; exit 1"},
                  {"name": b, "run": "true"},
                  {"name": c, "run": "sleep 5", "timeout": "1s"}, goal="g" * 50)
        code, out, _ = self.bb("run")
        self.assertEqual(code, 1)
        lines = out.splitlines()
        for i in range(6, 26):
            self.assertIn(f"    line {i}", lines)
        self.assertNotIn("    line 5", lines)
        code, status, _ = self.bb()
        self.assertNotIn("line ", status)
        self.assertIn("Goal    " + "g" * 50, status)
        self.write("big.toml", '[[check]]\nname = "%s"\nrun = "true"\n' % ("d" * 40))
        code, out, _ = self.bb("-f", "big.toml", "run")
        self.assertEqual(code, 0)

    def pty_status(self, no_color):
        env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"}
        env["TERM"] = "xterm"
        if no_color:
            env["NO_COLOR"] = "1"
        master, slave = pty.openpty()  # child's stdout on the slave end
        proc = subprocess.Popen([sys.executable, TOOL], cwd=self.dir, stdout=slave,
                                stderr=subprocess.DEVNULL, env=env)
        os.close(slave)
        data = b""
        while True:
            try:
                chunk = os.read(master, 4096)
            except OSError:
                break
            if not chunk:
                break
            data += chunk
        os.close(master)
        proc.wait()
        return data

    def test_bold_only_on_a_terminal(self):
        self.write("a.txt", "a\n")
        self.task({"name": "bad", "run": "false"}, {"name": "old", "run": "true", "watch": ["a.txt"]})
        self.bb("run")
        self.write("a.txt", "b\n")
        bold = self.pty_status(no_color=False)
        self.assertIn(b"\x1b[1mSTALE\x1b[0m", bold)
        self.assertIn(b"\x1b[1mFAILED\x1b[0m", bold)
        plain = self.pty_status(no_color=True)
        self.assertNotIn(b"\x1b", plain)
        self.assertIn(b"STALE", plain)


class Project(unittest.TestCase):
    def test_imports_are_stdlib(self):
        tree = ast.parse(slurp(TOOL))
        names = [a.name for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names]
        names += [n.module for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)]
        self.assertTrue(names)
        for name in names:
            self.assertIn(name.split(".")[0], sys.stdlib_module_names)

    def test_help_last_line(self):
        r = subprocess.run([sys.executable, TOOL, "--help"], capture_output=True, text=True)
        self.assertEqual(r.returncode, 0)
        self.assertEqual(r.stdout.splitlines()[-1],
                         "This does not make the work good. It makes the evidence recent.")

    def test_no_em_dash_or_emoji(self):
        bad = re.compile("[%s%s-%s%s-%s]" % tuple(map(chr, (0x2014, 0x2600, 0x27BF, 0x1F000, 0x1FAFF))))
        for root, dirs, files in os.walk(ROOT):
            dirs[:] = [d for d in dirs if d not in (".best-before", "__pycache__", ".venv", "shots")]
            for name in files:
                if name.endswith((".py", ".toml", ".md", ".txt", ".html", ".gitignore")):
                    text = slurp(os.path.join(root, name))
                    self.assertIsNone(bad.search(text), name)


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