"""Cue Light: runs a cue file one command at a time, Standby then Go, and files a show report."""

import argparse
import datetime
import os
import re
import shlex
import signal
import subprocess
import sys
import termios
import time
import tty

HEADER = re.compile(r"([0-9]+) +(.+)")
COMMAND = re.compile(r"[ \t]+\$ +(.+)")
KEYS = "Space is Standby. Enter is Go. Backspace stands down. q ends the show."
COLOUR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")


def brick(text):
    return f"\x1b[38;2;236;94;82m{text}\x1b[0m" if COLOUR else text


def bold(text):
    return f"\x1b[1m{text}\x1b[0m" if COLOUR else text


def say(line=""):
    print(line, flush=True)


def dur(seconds):
    tenths = round(seconds * 10)
    h, tenths = divmod(tenths, 36000)
    m, tenths = divmod(tenths, 600)
    s, tenth = divmod(tenths, 10)
    return f"{h}:{m:02}:{s:02}.{tenth}"


class Moment:
    """One instant on both clocks: the wall for the record, monotonic for the arithmetic."""

    def __init__(self):
        self.wall, self.mono = datetime.datetime.now().astimezone(), time.monotonic()


class Cue:
    def __init__(self, n, label, line):
        self.n, self.label, self.line, self.cmd = n, label, line, None
        self.standby = self.go = self.ran = self.exit = None
        self.refused, self.check, self.result = 0, "-", "not called"


class CueFileError(Exception):
    pass


def parse(path):
    def fail(message, line=None):
        raise CueFileError(f"{path}:{line}: {message}" if line else f"{path}: {message}")

    try:
        with open(path, "rb") as f:
            data = f.read()
    except OSError as e:
        fail(f"cannot read: {e.strerror}")
    try:
        text = data.decode("utf-8")
    except UnicodeDecodeError as e:
        fail("not UTF-8", data[: e.start].count(b"\n") + 1)
    title, cues = None, []
    for no, raw in enumerate(text.split("\n"), 1):
        line = raw.rstrip()
        if not line or line.lstrip().startswith("#"):
            continue
        if line[0] in " \t":
            m = COMMAND.fullmatch(line)
            if not m:
                fail("empty command" if line.strip() == "$" else "an indented line must be $ and a command", no)
            if not cues:
                fail("command before any cue", no)
            if cues[-1].cmd is not None:
                fail(f"cue {cues[-1].n} has a second command", no)
            cues[-1].cmd = m[1]
        elif line.startswith("Show: "):
            if title is not None:
                fail("second Show: line", no)
            if cues:
                fail("Show: must come before the first cue", no)
            title = line[6:].lstrip()
        elif m := HEADER.fullmatch(line):
            n = int(m[1])
            if cues and cues[-1].cmd is None:
                fail(f"cue {cues[-1].n} has no command", cues[-1].line)
            if n < 1:
                fail("cue numbers start at 1", no)
            if cues and n <= cues[-1].n:
                fail(f"cue {n} does not come after cue {cues[-1].n}", no)
            cues.append(Cue(n, m[2], no))
        else:
            fail("not a cue, a command, a comment or a Show: line", no)
    if not cues:
        fail("no cues")
    if cues[-1].cmd is None:
        fail(f"cue {cues[-1].n} has no command", cues[-1].line)
    return title or stem(path), cues


def stem(path):
    return os.path.splitext(os.path.basename(path))[0]


def check(cmd):
    """Rehearsal check: parse the command and look at its path, without running it."""
    if subprocess.run(["/bin/sh", "-n", "-c", cmd], stdin=subprocess.DEVNULL,
                      stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
        return "syntax error"
    try:
        word = shlex.split(cmd)[0]
    except (ValueError, IndexError):
        return "syntax ok"
    if "=" in word or word[:1] in "~$" or "/" not in word:
        return "syntax ok"
    if not os.path.exists(word):
        return f"not found: {word}"
    if not os.access(word, os.X_OK):
        return f"not executable: {word}"
    return "syntax ok, path ok"


def announce(cue):
    say(bold(f"Cue {cue.n} is next: {cue.label}"))
    say(f"  $ {cue.cmd}")


def run(cue, fd, cooked):
    """Live Go: the child gets the terminal as it was, and nothing typed meanwhile survives."""
    interrupted = []
    termios.tcsetattr(fd, termios.TCSADRAIN, cooked)
    previous = signal.signal(signal.SIGINT, lambda *_: interrupted.append(True))
    start = time.monotonic()
    try:
        code = subprocess.run(cue.cmd, shell=True).returncode
    finally:
        cue.ran = time.monotonic() - start
        signal.signal(signal.SIGINT, previous)
        termios.tcflush(fd, termios.TCIFLUSH)
        tty.setcbreak(fd)
    cue.exit = f"signal {-code}" if code < 0 else str(code)
    if interrupted:
        cue.result = "interrupted"
    else:
        cue.result = "done" if code == 0 else "FAILED"
    return bool(interrupted)


def perform(cues, rehearse, fd):
    """The key loop. Returns (outcome, exit code, curtain up)."""
    cooked = termios.tcgetattr(fd)
    tty.setcbreak(fd)
    up, i, armed = None, 0, False
    try:
        announce(cues[0])
        while i < len(cues):
            cue = cues[i]
            key = os.read(fd, 1)
            if key in (b"q", b"Q", b""):
                say(f"Show ended before cue {cue.n}.")
                return f"ended before cue {cue.n}", 3, up
            if key == b" " and not armed:
                armed, cue.standby = True, Moment()
                say(f"{brick('Standby')} {cue.n}.")
            elif key in (b"\x7f", b"\x08") and armed:
                armed = False
                say(f"Stand down {cue.n}.")
            elif key in (b"\r", b"\n") and not armed:
                cue.refused += 1
                say(f"{brick('Go refused.')} Cue {cue.n} has no Standby.")
            elif key in (b"\r", b"\n"):
                armed, cue.go = False, Moment()
                up = up or cue.go
                say(f"Go {cue.n}.")
                if rehearse:
                    say(f"Would run: {cue.cmd}")
                    cue.check, cue.result = check(cue.cmd), "rehearsed"
                    say(f"Check: {cue.check}")
                    say(f"Cue {cue.n} rehearsed.")
                elif run(cue, fd, cooked):
                    say(f"Cue {cue.n} interrupted.")
                    return f"interrupted during cue {cue.n}", 130, up
                else:
                    word = "done" if cue.result == "done" else brick("FAILED")
                    say(f"Cue {cue.n} {word}. Exit {cue.exit}. {dur(cue.ran)}.")
                    if cue.result == "FAILED":
                        say(f"The show is stopped at cue {cue.n}.")
                        return f"halted at cue {cue.n}", 1, up
                i += 1
                if i < len(cues):
                    say()
                    announce(cues[i])
        say("That was the last cue.")
        failed = sum(not c.check.startswith("syntax ok") for c in cues) if rehearse else 0
        return (f"complete, failed checks: {failed}" if failed else "complete"), int(bool(failed)), up
    except KeyboardInterrupt:
        say(f"Show interrupted before cue {cues[i].n}.")
        return f"interrupted before cue {cues[i].n}", 130, up
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, cooked)


def report(path, title, cues, rehearse, outcome, up, down):
    def field(key, value, width):
        return f"{key + ':':<{width}}{value}"

    def clock(moment):
        return moment.wall.strftime("%H:%M:%S") if moment else "-"

    stamp = "%Y-%m-%d %H:%M:%S %z"
    called = sum(c.go is not None for c in cues)
    header = [
        ("Production", title),
        ("Cue file", path),
        ("Called by", os.environ.get("USER") or os.environ.get("LOGNAME") or "unknown"),
        ("Curtain up", up.wall.strftime(stamp) if up else "-"),
        ("Curtain down", down.wall.strftime(stamp)),
        ("Running time", dur(down.mono - up.mono) if up else "-"),
        ("Interval", "none taken."),
        ("Cues", f"{len(cues)} listed, {called} called, {len(cues) - called} not called"),
        ("Outcome", outcome),
    ]
    lines = ["REHEARSAL REPORT" if rehearse else "SHOW REPORT", ""]
    lines += [field(k, v, 16) for k, v in header]
    for c in cues:
        held = dur(c.go.mono - c.standby.mono) if c.go else "-"
        body = [
            ("Command", c.cmd), ("Standby", clock(c.standby)), ("Go", clock(c.go)), ("Held", held),
            ("Ran", "-" if c.ran is None else dur(c.ran)), ("Exit", c.exit or "-"),
            ("Refused", c.refused), ("Check", c.check), ("Result", c.result),
        ]
        lines += ["", f"Cue {c.n}  {c.label}"] + ["  " + field(k, v, 10) for k, v in body]
    return "\n".join(lines)


def file_report(text, kind, path, down):
    base = f"{kind}-report-{stem(path)}-{down.wall.strftime('%Y%m%d-%H%M%S')}"
    for n in range(1, 1000):
        name = f"{base}.txt" if n == 1 else f"{base}-{n}.txt"
        try:
            with open(name, "x", encoding="utf-8") as f:
                f.write(text + "\n")
            return name
        except FileExistsError:
            continue
        except OSError as e:
            print(f"cuelight: cannot write report: {e.strerror}", file=sys.stderr)
            return None
    print("cuelight: cannot write report: too many reports with this name", file=sys.stderr)
    return None


def main():
    ap = argparse.ArgumentParser(
        prog="cuelight",
        description="Run the commands in a cue file one at a time: Space is Standby, Enter is Go.",
    )
    ap.add_argument("--rehearse", action="store_true", help="call every cue without running it, and check it")
    ap.add_argument("file", metavar="FILE", help="the cue file")
    args = ap.parse_args()
    try:
        title, cues = parse(args.file)
    except CueFileError as e:
        print(f"cuelight: {e}", file=sys.stderr)
        return 2
    fd = 0
    if not os.isatty(fd):
        print("cuelight: stdin is not a terminal", file=sys.stderr)
        return 2
    width = max(len(str(c.n)) for c in cues)
    say(title)
    count = f"{len(cues)} cue{'' if len(cues) == 1 else 's'}"
    say(f"{'Rehearsal' if args.rehearse else 'Live'}. {count}. {args.file}")
    say()
    for c in cues:
        say(f"  {c.n:>{width}}  {c.label}")
    say()
    say(KEYS)
    say()
    outcome, code, up = perform(cues, args.rehearse, fd)
    down = Moment()
    text = report(args.file, title, cues, args.rehearse, outcome, up, down)
    name = file_report(text, "rehearsal" if args.rehearse else "show", args.file, down)
    say()
    say(text)
    if name:
        say()
        say(f"Report: {name}")
    return code


if __name__ == "__main__":
    sys.exit(main())
