"""Acceptance checks 1 to 8 of the card, driving the real tool through a pty.

Every tool process starts in a fresh temporary directory, so no report lands in the project.
Run: uv run python -m unittest -v test_cuelight
"""

import os
import pty
import re
import select
import subprocess
import sys
import tempfile
import termios
import time
import unittest

import cuelight

HERE = os.path.dirname(os.path.abspath(__file__))
TOOL = os.path.join(HERE, "cuelight.py")
SHIP = os.path.join(HERE, "ship.cues")
ANSI = re.compile(rb"\x1b\[[0-9;]*m")


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


def numbered(*commands):
    """A cue file whose cues are 1, 2, 3 in file order."""
    return "".join(f"{n}  Cue {n}\n  $ {c}\n" for n, c in enumerate(commands, 1))


def field(text, key, cue=None):
    block = text.split("\n\nCue ")[0] if cue is None else text.split(f"\nCue {cue}  ")[1].split("\n\n")[0]
    return re.search(rf"(?m)^ *{key}: +(.*)$", block)[1]


def tenths(duration):
    h, m, s = duration.split(":")
    return round((int(h) * 3600 + int(m) * 60 + float(s)) * 10)


class Show:
    """The tool on the slave side of a fresh pty, the test on the master side."""

    def __init__(self, cwd, cuefile, *flags, colour=False):
        env = {k: v for k, v in os.environ.items() if k != "NO_COLOR"}
        if not colour:
            env["NO_COLOR"] = "1"
        self.cwd, self.raw, self.eof = cwd, b"", False
        self.pid, self.fd = pty.fork()
        if self.pid == 0:
            os.chdir(cwd)
            os.execve(sys.executable, [sys.executable, TOOL, *flags, cuefile], env)

    @property
    def screen(self):
        return ANSI.sub(b"", self.raw).decode().replace("\r\n", "\n")

    def pump(self, seconds):
        end = time.monotonic() + seconds
        while not self.eof and (left := end - time.monotonic()) > 0:
            if select.select([self.fd], [], [], left)[0]:
                try:
                    data = os.read(self.fd, 4096)
                except OSError:
                    data = b""
                self.eof = not data
                self.raw += data

    def wait_for(self, text, timeout=10, times=1):
        end = time.monotonic() + timeout
        while self.screen.count(text) < times:
            if self.eof or time.monotonic() > end:
                raise AssertionError(f"{text!r} not seen. Screen:\n{self.screen}")
            self.pump(0.05)

    def press(self, keys, expect):
        times = self.screen.count(expect) + 1
        os.write(self.fd, keys)
        self.wait_for(expect, times=times)

    def call(self, n):
        self.wait_for(f"Cue {n} is next:")
        self.press(b" ", f"Standby {n}.")
        self.press(b"\r", f"Go {n}.")

    def end(self, timeout=15):
        end = time.monotonic() + timeout
        while not self.eof and time.monotonic() < end:
            self.pump(0.1)
        _, status = os.waitpid(self.pid, 0)
        os.close(self.fd)
        return os.waitstatus_to_exitcode(status)

    def exists(self, name):
        return os.path.exists(os.path.join(self.cwd, name))


class CueLight(unittest.TestCase):
    def report(self, show, kind="show"):
        """Check 7 on every report: one Interval line, no escapes, printed once inside the report."""
        names = [f for f in os.listdir(show.cwd) if f.startswith(f"{kind}-report-")]
        self.assertEqual(len(names), 1, names)
        self.assertRegex(names[0], rf"^{kind}-report-\w+-\d{{8}}-\d{{6}}\.txt$")
        with open(os.path.join(show.cwd, names[0]), encoding="utf-8") as f:
            text = f.read()
        self.assertEqual(len(re.findall(r"(?m)^Interval:       none taken\.$", text)), 1)
        self.assertNotIn("\x1b", text)
        screen = show.screen
        self.assertIn("\n\n" + text + "\nReport: " + names[0] + "\n", screen)
        self.assertEqual(screen.count("Interval"), 1)
        self.assertGreater(screen.index("Interval"), screen.index("\n\n" + text.split("\n")[0] + "\n"))
        return text

    def test_1_bad_files(self):
        with tempfile.TemporaryDirectory() as d:
            for body, want in [
                ("10  A\n  $ true\n5  B\n  $ true\n", "{}:3: cue 5 does not come after cue 10"),
                ("10  A\n  $ true\n10  B\n  $ true\n", "{}:3: cue 10 does not come after cue 10"),
                ("10  A\n20  B\n  $ true\n", "{}:1: cue 10 has no command"),
                ("# only\n\n# comments\n", "{}: no cues"),
            ]:
                path = write(d, "bad.cues", body)
                r = subprocess.run([sys.executable, TOOL, path], cwd=d, stdin=subprocess.DEVNULL,
                                   capture_output=True, text=True)
                self.assertEqual((r.returncode, r.stdout, r.stderr), (2, "", f"cuelight: {want.format(path)}\n"))
            r = subprocess.run([sys.executable, TOOL, SHIP], cwd=d, stdin=subprocess.DEVNULL,
                               capture_output=True, text=True)
            self.assertEqual((r.returncode, r.stderr), (2, "cuelight: stdin is not a terminal\n"))
            self.assertEqual(os.listdir(d), ["bad.cues"])

    def test_2_guard(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "guard.cues", numbered("touch marker1", "true")), colour=True)
            show.wait_for("$ touch marker1")
            show.press(b"\r", "Go refused. Cue 1 has no Standby.")
            show.pump(0.3)
            self.assertFalse(show.exists("marker1"))
            show.press(b" ", "Standby 1.")
            show.press(b"\r", "Cue 2 is next:")
            self.assertIn("Go 1.\nCue 1 done. Exit 0. ", show.screen)
            self.assertTrue(show.exists("marker1"))
            show.press(b"\r", "Go refused. Cue 2 has no Standby.")
            show.press(b" ", "Standby 2.")
            show.press(b"\x7f", "Stand down 2.")
            show.press(b"\r", "Go refused. Cue 2 has no Standby.")
            self.assertIn(b"\x1b[38;2;236;94;82mStandby\x1b[0m 1.", show.raw)
            self.assertIn(b"\x1b[38;2;236;94;82mGo refused.\x1b[0m Cue 1", show.raw)
            show.press(b"q", "Show ended before cue 2.")
            self.assertEqual(show.end(), 3)
            text = self.report(show)
            self.assertEqual([field(text, "Refused", n) for n in (1, 2)], ["1", "2"])
            self.assertEqual(field(text, "Outcome"), "ended before cue 2")

    def test_3_type_ahead_discarded(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "ahead.cues", numbered("sleep 2", "touch marker2")))
            show.call(1)
            show.pump(0.5)
            os.write(show.fd, b" ")
            show.pump(0.2)
            os.write(show.fd, b"\r")
            show.wait_for("Cue 1 done.")
            show.pump(1)
            self.assertFalse(show.exists("marker2"))
            self.assertNotIn("Go 2.", show.screen)
            show.press(b"q", "Report: ")
            self.assertEqual(show.end(), 3)
            self.assertEqual(field(self.report(show), "Result", 2), "not called")

    def test_3b_double_tap_in_one_write(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "tap.cues", "10  Sleep\n  $ sleep 1\n20  Touch\n  $ touch marker2\n"))
            show.wait_for("$ sleep 1")
            os.write(show.fd, b" \r \r")
            show.wait_for("Cue 10 done.")
            show.pump(1)
            self.assertFalse(show.exists("marker2"))
            self.assertNotIn("Go 20.", show.screen)
            show.press(b"q", "Report: ")
            self.assertEqual(show.end(), 3)
            self.report(show)

    def test_3c_keys_read_from_descriptor(self):
        with open(TOOL) as f:
            lines = f.readlines()
        self.assertEqual(sum(bool(re.search(r"sys\.stdin\.read", line)) for line in lines), 0)
        self.assertGreaterEqual(sum("os.read" in line for line in lines), 1)

    def test_4_failure_halts(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "halt.cues", numbered("true", "exit 7", "touch marker3")))
            show.call(1)
            show.call(2)
            show.wait_for("The show is stopped at cue 2.")
            self.assertEqual(show.end(), 1)
            self.assertIn("Cue 2 FAILED. Exit 7. ", show.screen)
            self.assertNotIn("Cue 3 is next", show.screen)
            self.assertNotIn(b"\x1b[", show.raw)
            self.assertFalse(show.exists("marker3"))
            text = self.report(show)
            self.assertEqual((field(text, "Exit", 2), field(text, "Result", 2)), ("7", "FAILED"))
            self.assertEqual(field(text, "Result", 3), "not called")
            self.assertEqual(field(text, "Outcome"), "halted at cue 2")

    def test_5_ctrl_c_during_cue(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "long.cues", numbered("sleep 30")))
            show.call(1)
            show.pump(0.5)
            os.write(show.fd, b"\x03")
            show.wait_for("Cue 1 interrupted.", timeout=3)
            show.wait_for("Report: ")
            echo = termios.tcgetattr(show.fd)[3] & termios.ECHO
            self.assertEqual(show.end(), 130)
            self.assertTrue(echo, "terminal left without echo")
            text = self.report(show)
            self.assertEqual(field(text, "Result", 1), "interrupted")
            self.assertEqual(field(text, "Outcome"), "interrupted during cue 1")

    def test_5b_ctrl_c_while_waiting(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "idle.cues", numbered("true")))
            show.wait_for("$ true")
            os.write(show.fd, b"\x03")
            show.wait_for("Show interrupted before cue 1.", timeout=3)
            self.assertEqual(show.end(), 130)
            text = self.report(show)
            self.assertEqual((field(text, "Curtain up"), field(text, "Running time")), ("-", "-"))
            self.assertEqual(field(text, "Outcome"), "interrupted before cue 1")

    def test_6_rehearsal(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "rehearse.cues", numbered("touch marker4", "./nope.sh", "echo (")), "--rehearse")
            for n in (1, 2, 3):
                show.call(n)
            show.wait_for("That was the last cue.")
            self.assertEqual(show.end(), 1)
            self.assertFalse(show.exists("marker4"))
            self.assertIn("Go 2.\nWould run: ./nope.sh\nCheck: not found: ./nope.sh\nCue 2 rehearsed.\n", show.screen)
            text = self.report(show, "rehearsal")
            self.assertEqual(text.split("\n")[0], "REHEARSAL REPORT")
            self.assertEqual([field(text, "Check", n) for n in (1, 2, 3)],
                             ["syntax ok", "not found: ./nope.sh", "syntax error"])
            self.assertEqual(field(text, "Outcome"), "complete, failed checks: 2")
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, SHIP, "--rehearse")
            for n in (10, 20, 30):
                show.call(n)
            show.wait_for("That was the last cue.")
            self.assertEqual(show.end(), 0)
            text = self.report(show, "rehearsal")
            self.assertEqual(field(text, "Outcome"), "complete")
            checks = re.findall(r"(?m)^  Check: +(.*)$", text)
            self.assertEqual(len(checks), 3)
            self.assertTrue(all(c.startswith("syntax ok") for c in checks), checks)

    def test_6b_path_checks(self):
        with tempfile.TemporaryDirectory() as d:
            plain, script = write(d, "plain.txt", ""), write(d, "go.sh", "true\n")
            os.chmod(script, 0o755)
            self.assertEqual(cuelight.check(plain), f"not executable: {plain}")
            self.assertEqual(cuelight.check(f"{script} --now"), "syntax ok, path ok")
            for cmd in ("A=1 ./x", "~/x", "$HOME/x", "ls -l", "'' x", "echo 'open"):
                self.assertEqual(cuelight.check(cmd), "syntax error" if cmd == "echo 'open" else "syntax ok", cmd)

    def test_7_interval_constant_while_held(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "held.cues", numbered("true")))
            show.wait_for("$ true")
            show.press(b" ", "Standby 1.")
            show.pump(2.1)
            show.press(b"\r", "Report: ")
            self.assertEqual(show.end(), 0)
            text = self.report(show)
            self.assertGreaterEqual(tenths(field(text, "Held", 1)), 20)
            self.assertEqual(field(text, "Interval"), "none taken.")
        with open(TOOL) as f:
            self.assertEqual(sum("Interval" in line for line in f), 1)

    def test_8_report_precision(self):
        with tempfile.TemporaryDirectory() as d:
            show = Show(d, write(d, "timing.cues", numbered("sleep 1")))
            show.wait_for("$ sleep 1")
            show.press(b" ", "Standby 1.")
            show.pump(1.5)
            show.press(b"\r", "Report: ")
            self.assertEqual(show.end(), 0)
            text = self.report(show)
            lines = text.split("\n")
            self.assertEqual(lines[0], "SHOW REPORT")
            ran, held = tenths(field(text, "Ran", 1)), tenths(field(text, "Held", 1))
            self.assertTrue(10 <= ran <= 15, ran)
            self.assertTrue(14 <= held <= 20, held)
            self.assertGreaterEqual(tenths(field(text, "Running time")), ran)
            for key in ("Curtain up", "Curtain down"):
                self.assertRegex(field(text, key), r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4}$")
            header = lines[lines.index("") + 1:lines.index("", 2)]
            self.assertEqual((header[0][:11], header[-1][:8]), ("Production:", "Outcome:"))
            for line in header:
                self.assertRegex(line, r"^[A-Z][A-Za-z ]+: +\S")
                self.assertRegex(line, r"^.{15} \S")
            for line in (line for line in lines if line.startswith("  ")):
                self.assertRegex(line, r"^  [A-Z][a-z]+: +\S")
                self.assertRegex(line, r"^.{11} \S")

    def test_8b_durations(self):
        self.assertEqual([cuelight.dur(s) for s in (0, 0.04, 0.35, 59.96, 3725.26)],
                         ["0:00:00.0", "0:00:00.0", "0:00:00.4", "0:01:00.0", "1:02:05.3"])


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