#!/usr/bin/env -S python3 -X utf8
# summary: Render or play the terminal greeting scene.
"""The terminal greeting's pixel scene: a teal ship flies left to right and shoots coral aliens.

It is drawn with half-block characters (two pixels per cell) in 24-bit or 256 colors and never paints a
background block, so it reads on light and dark terminals. The scene is seeded: every run is the same.

  starchaser intro rest              print the resting frame (the logo that stays on screen)
  starchaser intro frame N           print animation frame N
  starchaser intro count             print the number of frames
  starchaser intro play --up U --col C
                                     animate in place: move up U lines, start at column C, end on the resting frame
  starchaser intro locate FILE --col C
                                     after FILE was printed, ask the terminal where its logo is; print play options
  starchaser intro play --top T --col C --width W --size ROWSxCOLUMNS
                                     animate at row T while the shell reads the keyboard (the greeting's shell hook)
Options: --color truecolor|256|auto   --light   --dark   --fps N
"""
import argparse
import math
import os
import random
import re
import select
import signal
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import CommandParser, safe_streams
safe_streams()

W, H = 26, 24              # pixels; the picture is W cells wide and H / 2 lines tall
ROWS = H // 2
FPS, FRAMES = 24, 96       # about four seconds
REST_X, REST_Y = 9, 8      # where the ship ends

DARK = {"ship": (38, 166, 154), "ship2": (128, 222, 210), "alien": (239, 83, 80), "alien2": (255, 160, 140),
        "star": (90, 90, 120), "star2": (150, 150, 185)}
LIGHT = {"ship": (0, 128, 118), "ship2": (22, 172, 156), "alien": (214, 64, 60), "alien2": (236, 120, 100),
         "star": (190, 190, 210), "star2": (140, 140, 170)}

SHIP = ["XX.....",
        "XXX....",
        ".XXXXX.",
        ".XXXXXX",
        ".XXXXX.",
        "XXX....",
        "XX....."]

# Three aliens, two frames each (they wiggle). X is a pixel, o is a lighter pixel.
ALIENS = [
    (["..XXX..", ".XXXXX.", ".XoXoX.", ".XXXXX.", "..X.X.."],
     ["..XXX..", ".XXXXX.", ".XoXoX.", ".XXXXX.", ".X...X."]),
    (["X.XXX.X", "XXXXXXX", "XXoXoXX", "XXXXXXX", "X.....X"],
     [".XXXXX.", "XXXXXXX", "XXoXoXX", "XXXXXXX", ".X...X."]),
    (["XX.X.XX", "XXXXXXX", "XoXXXoX", ".XXXXX.", "X.X.X.X"],
     ["XX.X.XX", "XXXXXXX", "XoXXXoX", ".XXXXX.", ".X.X.X."]),
]

# (frame to appear, alien shape, top row): staggered so the ship has time to line up each shot
SPAWNS = [(8, 0, 6), (16, 1, 12), (24, 2, 5), (32, 0, 13), (40, 1, 8), (48, 2, 4), (56, 0, 10)]
STARS = 14


def ship_x(f):
    """Fast fly-in from the left, then a slow cruise to the resting spot: always moving right."""
    if f < 14:
        return -7 + f * 0.9
    return 5.6 + (f - 14) * (REST_X - 5.6) / (FRAMES - 1 - 14)


def simulate():
    """Run the whole scene once. Returns one dictionary of things to draw per frame."""
    rnd = random.Random(7)
    stars = [[rnd.uniform(0, W), rnd.randrange(H), rnd.choice((0.5, 0.5, 1.0, 1.8))] for _ in range(STARS)]
    ship_y = float(REST_Y)
    aliens, shots, sparks = [], [], []
    frames = []
    for f in range(FRAMES):
        sx = ship_x(f)
        sy = ship_y + (0.6 * math.sin(f / 5) if f < FRAMES - 12 else 0)
        frames.append({"stars": [tuple(s) for s in stars], "ship": (sx, sy),
                       "aliens": [tuple(a) for a in aliens], "shots": [tuple(m) for m in shots],
                       "sparks": [(p[0], p[1], p[4]) for p in sparks]})
        for s in stars:
            s[0] -= s[2] * 1.4
            if s[0] < 0:
                s[0] += W
                s[1] = rnd.randrange(H)
        for when, shape, row in SPAWNS:
            if f == when:
                aliens.append([W + 1.0, row, shape])
        for a in aliens:
            a[0] -= 0.4
        ahead = [a for a in aliens if a[0] > sx + 9]
        goal = REST_Y
        if ahead and f <= FRAMES - 12:
            goal = min(ahead, key=lambda a: a[0])[1] + 2 - 3
        ship_y += max(-1.0, min(1.0, goal - ship_y))
        if ahead and f % 3 == 0 and abs(goal - ship_y) < 1.2 and f < FRAMES - 14 and len(shots) < 3:
            shots.append([sx + 7, sy + 3])
        for m in shots:
            m[0] += 2.4
        for m in shots[:]:
            for a in aliens[:]:
                if a[0] - 1 <= m[0] <= a[0] + 7 and a[1] - 1 <= m[1] <= a[1] + 5:
                    aliens.remove(a)
                    shots.remove(m)
                    for _ in range(12):
                        angle = rnd.uniform(0, 2 * math.pi)
                        speed = rnd.uniform(0.4, 1.4)
                        sparks.append([a[0] + 3, a[1] + 2, speed * math.cos(angle) + 0.3,
                                       speed * math.sin(angle) * 0.7, rnd.randint(6, 12)])
                    break
        shots[:] = [m for m in shots if m[0] < W]
        aliens[:] = [a for a in aliens if a[0] > -8]
        for p in sparks:
            p[0] += p[2]
            p[1] += p[3]
            p[4] -= 1
        sparks[:] = [p for p in sparks if p[4] > 0]
    return frames


_FRAMES = None


def frames():
    global _FRAMES
    if _FRAMES is None:
        _FRAMES = simulate()
    return _FRAMES


def put(px, x, y, color):
    x, y = math.floor(x + 0.5), math.floor(y + 0.5)
    if 0 <= x < W and 0 <= y < H:
        px[y][x] = color


def draw_ship(px, pal, sx, sy, f):
    bx, by = math.floor(sx + 0.5), math.floor(sy + 0.5)
    for r, row in enumerate(SHIP):
        for c, ch in enumerate(row):
            if ch == "X":
                put(px, bx + c, by + r, pal["ship2"] if (r == 3 and c >= 5) else pal["ship"])
    # the engine flickers: a coral spark behind the ship, long, short or off
    flame = (f // 2) % 3
    if flame:
        put(px, bx - 1, by + 3, pal["alien2"])
    if flame == 2:
        put(px, bx - 2, by + 3, pal["alien"])


def rest_pixels(pal):
    """The resting frame: a few still stars, the ship, and the last burst fading out."""
    px = [[None] * W for _ in range(H)]
    for x, y, speed in ((2, 3, 0.5), (20, 2, 1.0), (14, 6, 0.5), (24, 10, 1.8), (4, 19, 1.0), (11, 21, 0.5),
                        (19, 17, 0.5), (23, 22, 1.0), (7, 0, 0.5)):
        put(px, x, y, pal["star2"] if speed > 1.5 else pal["star"])
    for x, y, bright in ((22, 11, True), (21, 9, False), (24, 13, False), (20, 13, False), (23, 8, False)):
        put(px, x, y, pal["alien2"] if bright else pal["alien"])
    draw_ship(px, pal, REST_X, REST_Y, 2)  # a steady engine, not a flicker
    return px


def frame_pixels(n, pal):
    if n >= FRAMES - 1:
        return rest_pixels(pal)
    data = frames()[n]
    px = [[None] * W for _ in range(H)]
    for x, y, speed in data["stars"]:
        put(px, x, y, pal["star2"] if speed > 1.5 else pal["star"])
    draw_ship(px, pal, data["ship"][0], data["ship"][1], n)
    wiggle = (n // 6) % 2
    for x, y, shape in data["aliens"]:
        bx = math.floor(x + 0.5)
        for r, row in enumerate(ALIENS[shape][wiggle]):
            for c, ch in enumerate(row):
                if ch != ".":
                    put(px, bx + c, y + r, pal["alien2"] if ch == "o" else pal["alien"])
    for x, y in data["shots"]:
        put(px, x, y, pal["ship2"])
        put(px, x - 1, y, pal["ship"])
    for x, y, life in data["sparks"]:
        put(px, x, y, pal["alien"] if life > 4 else pal["alien2"])
    return px


def nearest256(rgb):
    """The closest xterm-256 color: the 6x6x6 cube or the gray ramp."""
    levels = (0, 95, 135, 175, 215, 255)
    cube = [min(range(6), key=lambda i: abs(levels[i] - v)) for v in rgb]
    cube_rgb = [levels[i] for i in cube]
    best = (sum((a - b) ** 2 for a, b in zip(rgb, cube_rgb)), 16 + 36 * cube[0] + 6 * cube[1] + cube[2])
    gray = max(0, min(23, round((sum(rgb) / 3 - 8) / 10)))
    value = 8 + 10 * gray
    if sum((a - value) ** 2 for a in rgb) < best[0]:
        return 232 + gray
    return best[1]


def color_code(rgb, ground, mode):
    base = 38 if ground == "fg" else 48
    if mode == "truecolor":
        return f"\033[{base};2;{rgb[0]};{rgb[1]};{rgb[2]}m"
    return f"\033[{base};5;{nearest256(rgb)}m"


def render(px, mode):
    """Pixels to text lines. A lower pixel uses the background only where there is a pixel, so empty
    cells keep the terminal's own background."""
    lines = []
    for y in range(0, H, 2):
        out = []
        dirty = False
        for x in range(W):
            top, bottom = px[y][x], px[y + 1][x]
            if top is None and bottom is None:
                if dirty:
                    out.append("\033[0m")
                    dirty = False
                out.append(" ")
                continue
            if top is not None and bottom is not None and top != bottom:
                out.append("\033[0m" + color_code(top, "fg", mode) + color_code(bottom, "bg", mode) + "▀")
            elif top is not None and bottom is not None:
                out.append("\033[0m" + color_code(top, "fg", mode) + "█")
            elif top is not None:
                out.append("\033[0m" + color_code(top, "fg", mode) + "▀")
            else:
                out.append("\033[0m" + color_code(bottom, "fg", mode) + "▄")
            dirty = True
        if dirty:
            out.append("\033[0m")
        lines.append("".join(out))
    return lines


def color_mode(choice):
    if choice in ("truecolor", "256"):
        return choice
    return "truecolor" if os.environ.get("COLORTERM", "").lower() in ("truecolor", "24bit") else "256"


def light_theme():
    state = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"),
                         "starchaser", "theme.json")
    try:
        with open(state, encoding="utf-8") as handle:
            return re.search(r'"variant"\s*:\s*"light"', handle.read()) is not None
    except OSError:
        return False


class Keys:
    """Notice that a key was typed, without reading it and without echoing it.

    The scene only polls the keyboard. Every typed byte stays in the terminal's queue for the prompt, so
    nothing typed during the scene is lost or split (arrow keys and letters such as e-acute arrive whole)."""

    def __init__(self, fd):
        self.fd = fd
        self.saved = None

    def __enter__(self):
        try:
            import termios
            import tty
            self.saved = termios.tcgetattr(self.fd)
            tty.setcbreak(self.fd, termios.TCSANOW)  # NOW: a flush would drop what was typed ahead
        except Exception:
            self.saved = None
        return self

    def __exit__(self, *exc):
        if self.saved is not None:
            import termios
            # NOW, never DRAIN or FLUSH: nothing that was typed may be dropped.
            termios.tcsetattr(self.fd, termios.TCSANOW, self.saved)
            self.saved = None

    def pressed(self):
        if self.saved is None:
            return False
        return bool(select.select([self.fd], [], [], 0)[0])


ROOM = 4                   # empty lines the prompt needs below the details: a two-line prompt and a wrapped command
REPLY = re.compile(rb"\x1b\[(\d+);(\d+)R")


def text_size(path):
    """Lines and widest line of what was printed, in terminal cells (the details are one cell per character).
    Lines are counted by their line breaks: fastfetch ends with escape codes after the last one."""
    with open(path, encoding="utf-8", errors="replace") as handle:
        text = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07", "", handle.read())
    return text.count("\n"), max(len(line) for line in text.split("\n"))


def window_size(fd):
    import fcntl
    import struct
    import termios
    rows, columns = struct.unpack("HHHH", fcntl.ioctl(fd, termios.TIOCGWINSZ, bytes(8)))[:2]
    return rows, columns


def cursor_row(fd, timeout=0.5):
    """Ask the terminal which row the cursor is on. None if a key is already waiting (it is left for the shell),
    if the terminal does not answer, or if a key arrived ahead of the answer."""
    import termios
    saved = termios.tcgetattr(fd)
    attrs = termios.tcgetattr(fd)
    # Read the answer byte by byte and silently; NOW, never FLUSH: keys typed after the answer stay for the shell.
    # Line by line, a half-typed line would not count as waiting, so look for keys only after the switch.
    attrs[3] &= ~(termios.ICANON | termios.ECHO)
    attrs[6][termios.VMIN], attrs[6][termios.VTIME] = 1, 0
    reply = b""
    try:
        termios.tcsetattr(fd, termios.TCSANOW, attrs)
        if select.select([fd], [], [], 0)[0]:
            return None
        os.write(fd, b"\x1b[6n")
        end = time.monotonic() + timeout
        while not reply.endswith(b"R") and len(reply) < 32:
            left = end - time.monotonic()
            if left <= 0 or not select.select([fd], [], [], left)[0]:
                break
            reply += os.read(fd, 1)
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, saved)
    match = REPLY.fullmatch(reply)
    return int(match.group(1)) if match else None


def locate(args):
    """The play options for the scene beside FILE, just printed above the cursor; exit 1 where it must not play."""
    fd = sys.stdin.fileno()
    try:
        lines, width = text_size(args.file)
        rows, columns = window_size(fd)
        # The logo starts on the first printed line, and the prompt needs room below so nothing scrolls it away.
        if lines < ROWS or lines + 1 + ROOM > rows:
            sys.exit(1)
        row = cursor_row(fd)
    except (OSError, ValueError, ImportError):
        sys.exit(1)
    if row is None or row - lines < 1 or row + ROOM > rows:
        sys.exit(1)
    print(f"--top {row - lines} --col {args.col} --width {width} --size {rows}x{columns}")


def play_beside_prompt(args):
    """The scene while the shell reads the keyboard. Each frame is one write that saves the cursor, draws at the
    logo's place and puts the cursor back, so the prompt and what is being typed stay put. It never reads the
    keyboard or changes the terminal's settings. It stops, on the resting frame, when the shell is about to run a
    command (SIGTERM from the shell hook), and without drawing again where the logo may have moved."""
    mode = color_mode(args.color)
    pal = LIGHT if args.light else DARK
    fd = sys.stdout.fileno()
    parent = os.getppid()
    stop, resized = [], []

    def note(signum, _frame):
        stop.append(signum)

    for name in ("SIGTERM", "SIGINT", "SIGQUIT", "SIGHUP"):
        signal.signal(getattr(signal, name), note)
    signal.signal(signal.SIGWINCH, lambda *_: resized.append(1))
    # It shares the shell's process group: Ctrl-Z at the prompt must not stop it while the shell waits for it.
    for name in ("SIGTSTP", "SIGTTIN", "SIGTTOU"):
        signal.signal(getattr(signal, name), signal.SIG_IGN)

    def size():
        try:
            return window_size(fd)
        except OSError:
            return None

    def draw(lines):
        data = ["\x1b[?2026h\x1b7"]
        for number, line in enumerate(lines):
            data.append(f"\x1b[{args.top + number};{args.col}H{line}")
        data.append("\x1b8\x1b[?2026l")
        data = "".join(data).encode()
        while data:
            data = data[os.write(fd, data):]

    rest = render(rest_pixels(pal), mode)
    drawn = []
    for n in range(FRAMES):
        if stop or resized or os.getppid() != parent or size() != args.size:
            break
        drawn.append(render(frame_pixels(n, pal), mode))
    if size() != args.size:
        return
    try:
        start = time.monotonic()
        for n, frame in enumerate(drawn):
            if stop or resized or os.getppid() != parent or size() != args.size:
                break
            draw(frame)
            delay = start + (n + 1) / args.fps - time.monotonic()
            if delay > 0:
                time.sleep(delay)
        now = size()
        if signal.SIGHUP in stop or os.getppid() != parent or now is None:
            return
        if now != args.size:
            # A taller window that is still wide enough for every printed line leaves a logo that starts on the
            # first line where it was; anything else may have reflowed or scrolled, so draw nothing more.
            if not (args.top == 1 and now[0] >= args.size[0] and now[1] >= args.width):
                return
        draw(rest)
    except OSError:
        pass


def play(args):
    if args.top:
        play_beside_prompt(args)
        return
    mode = color_mode(args.color)
    pal = LIGHT if args.light else DARK
    out = sys.stdout
    col = f"\033[{args.col}G"
    # kitty decides "is a program running?" from the prompt mark on the cursor's line. Every frame ends with the
    # cursor back at the top line's left edge, so mark that line again each time: the window always reads as at a prompt.
    # kitty's bash integration unsets KITTY_SHELL_INTEGRATION before ~/.bashrc runs, so its absence means nothing here;
    # only an explicit no-prompt-mark (seen when it is still set) turns the marks off (same rule as the greeting hook).
    integration = os.environ.get("KITTY_SHELL_INTEGRATION", "")
    marking = bool(os.environ.get("KITTY_WINDOW_ID")) and "no-prompt-mark" not in integration
    prompt_mark = "\033]133;A\007" if marking else ""

    def paint(lines):
        for number, line in enumerate(lines):
            out.write(col + line + ("\033[B" if number < len(lines) - 1 else ""))
        out.write(f"\033[{len(lines) - 1}A\r" + prompt_mark)
        out.flush()

    stop = []

    def interrupt(signum, _frame):
        # Only note it: the scene ends at the next frame (within 1/24 s) and cleanup always runs whole.
        stop.append(signum)

    for name in ("SIGINT", "SIGTERM", "SIGHUP"):
        try:
            signal.signal(getattr(signal, name), interrupt)
        except (ValueError, OSError):
            pass
    keys = Keys(sys.stdin.fileno()) if sys.stdin.isatty() else None
    # Build every frame before touching the screen, so the greeting never stutters.
    drawn = [render(frame_pixels(n, pal), mode) for n in range(FRAMES)]
    if stop:
        return
    try:
        # kitty treats a window whose cursor is hidden as running a program, however it is marked: closing it
        # during the scene asked "It is running: python3". There the cursor stays visible (at the line's left edge,
        # left of the ship) and the shell's prompt mark, sent by the greeting hook, does the rest.
        hide = "" if os.environ.get("KITTY_WINDOW_ID") else "\033[?25l"
        out.write(hide + (f"\033[{args.up}A" if args.up else ""))
        if keys:
            keys.__enter__()
        start = time.monotonic()
        for n in range(FRAMES):
            paint(drawn[n])
            if stop or (keys and keys.pressed()):
                break
            delay = start + (n + 1) / args.fps - time.monotonic()
            if delay > 0:
                time.sleep(delay)
            if stop:
                break
    except OSError:
        pass
    finally:
        if keys:
            keys.__exit__()
        # Always give the screen back: the resting frame, cursor below the info, visible, colors reset.
        try:
            paint(drawn[-1])
            if args.up:
                out.write(f"\033[{args.up}B")
            out.write("\r\033[0m\033[?25h")
            out.flush()
        except OSError:
            pass


def frame_rate(value):
    try:
        rate = float(value)
    except ValueError:
        rate = 0
    if not math.isfinite(rate) or rate <= 0:
        raise argparse.ArgumentTypeError("Frame rate must be a positive, finite number.")
    return rate


def window(value):
    match = re.fullmatch(r"([1-9][0-9]{0,4})x([1-9][0-9]{0,4})", value)
    if not match:
        raise argparse.ArgumentTypeError("Size must be ROWSxCOLUMNS, for example 40x120.")
    return int(match.group(1)), int(match.group(2))


def main(argv=None):
    parser = CommandParser(prog="starchaser intro", description=__doc__,
                            formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("command", choices=("rest", "frame", "play", "count", "locate"), help="choose what to show (see commands above)")
    parser.add_argument("number", nargs="?", default=None, help="frame number, starting at 0 (default: 0; used by frame), or locate's FILE")
    parser.add_argument("--color", choices=("auto", "truecolor", "256"), default="auto",
                        help="color mode: detect from the terminal, full color, or 256 colors (default: auto)")
    parser.add_argument("--light", action="store_true", default=None, help="use colors for a light background (default: follow the saved theme)")
    parser.add_argument("--dark", dest="light", action="store_false", help="use colors for a dark background")
    parser.add_argument("--up", type=int, default=0, help="start this many terminal lines above the current line (play only; default: 0)")
    parser.add_argument("--col", type=int, default=1, help="start at this terminal column, counting from 1 (play only; default: 1)")
    parser.add_argument("--top", type=int, default=0, help="play beside the prompt with the logo's top on this row (play only)")
    parser.add_argument("--width", type=int, default=0, help="the widest printed line beside the logo (play --top only)")
    parser.add_argument("--size", type=window, default=None, help="the window's ROWSxCOLUMNS when it was printed (play --top only)")
    parser.add_argument("--fps", type=frame_rate, default=os.environ.get("STARCHASER_INTRO_FPS") or str(FPS),
                        help="frames per second for play (default: STARCHASER_INTRO_FPS, or 24 if unset)")
    args = parser.parse_args(argv)
    if args.command == "locate":
        if args.number is None:
            parser.error("locate needs the file that was printed.")
        args.file = args.number
    elif not re.fullmatch(r"-?[0-9]+", args.number or "0"):
        parser.error(f"Frame number must be a number, not '{args.number}'.")
    else:
        args.number = int(args.number or 0)
    if args.top and (args.top < 0 or args.col < 1 or args.size is None):
        parser.error("play --top needs a row, a column and --size ROWSxCOLUMNS.")
    if args.command == "frame" and not 0 <= args.number < FRAMES:
        parser.error(f"Frame number must be 0 to {FRAMES - 1}. Use starchaser intro count to see the number of frames.")
    if args.light is None:
        args.light = light_theme()
    if args.command == "count":
        print(FRAMES)
    elif args.command == "play":
        play(args)
    elif args.command == "locate":
        locate(args)
    else:
        pal = LIGHT if args.light else DARK
        pixels = rest_pixels(pal) if args.command == "rest" else frame_pixels(args.number, pal)
        print("\n".join(render(pixels, color_mode(args.color))))


if __name__ == "__main__":
    main()
