#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# dependencies = []
# ///
"""margin: reads one line and rings as it nears the right margin.

The keyboard is read from stdin. Every echo and every bell goes to /dev/tty.
Only the finished line goes to stdout, so `git commit -m "$(margin)"` works.
"""

import codecs
import fcntl
import os
import select
import signal
import struct
import sys
import termios
import time
import tty
import unicodedata

DEFAULT_WIDTH = 72
WARNING = 5  # characters before the stop; a choice, not a measurement
FLASH_SECONDS = 0.08

RETURN, BACKSPACE, KILL_LINE, KILL_WORD = "\r", "\x7f", "\x15", "\x17"
INTERRUPT, END = "\x03", "\x04"
NAMED = {RETURN, BACKSPACE, KILL_LINE, KILL_WORD, INTERRUPT, END}
ESC, BEL = "\x1b", "\x07"
FLASH_ON, FLASH_OFF = "\x1b[?5h", "\x1b[?5l"

HELP = """\
usage: margin [--flash] [WIDTH]
       margin --ring [--flash]

Reads one line. Rings near the margin, and at it.
Writes the line to standard output when you press
Return.

  WIDTH     the margin, in characters (default 72)
  --flash   flash the screen instead of ringing
  --ring    ring once and exit, to check the bell
  --help    this card

The bell rings five characters before the margin,
once at the margin, and on every key past it.

No counter is supplied.

Return delivers the line. Backspace, Ctrl-U and
Ctrl-W erase. Ctrl-C withdraws the line. Arrow
keys, Esc and Tab do nothing.

The margin is a suggestion. Typing past it is
permitted and will be rung.

normal is dead
"""

FOOTNOTE = {
    False: "Rung once. If you heard nothing, the bell is switched off, "
    "and the margin will go unmarked.",
    True: "Flashed once. If you saw nothing, this terminal does not flash, "
    "and the margin will go unmarked.",
}


class Usage(Exception):
    pass


# The pure part: no terminal below this line until the terminal layer.


def count(text, stop=None):
    """Characters as a person counts them: code points, combining marks count zero.

    Counting ends at `stop`, so one key costs at most WIDTH steps however long the line.
    """
    if text.isascii():
        return len(text) if stop is None else min(len(text), stop)
    n = 0
    for c in text:
        n += not unicodedata.combining(c)
        if n == stop:
            break
    return n


def press(buf, key, width):
    """Applies one key (a single character) to the buffer. Returns (buffer, bells)."""
    if key == BACKSPACE:
        end = len(buf)
        while end and unicodedata.combining(buf[end - 1]):
            end -= 1
        return buf[: max(end - 1, 0)], 0
    if key == KILL_LINE:
        return "", 0
    if key == KILL_WORD:
        kept = buf.rstrip()
        cut = len(kept)
        while cut and not kept[cut - 1].isspace():
            cut -= 1
        return kept[:cut], 0
    grew = not unicodedata.combining(key)
    n = count(buf, width) + grew  # exact below the stop, which is all the bell needs
    return buf + key, int(grew and (n == max(width - WARNING, 1) or n >= width))


def split_keys(chunk):
    """Splits one decoded chunk into keys. Escape sequences and other controls are dropped."""
    keys, i = [], 0
    while i < len(chunk):
        c = chunk[i]
        if c == ESC:
            after = chunk[i + 1 : i + 2]
            if after == "[":
                i += 2
                while i < len(chunk) and not "@" <= chunk[i] <= "~":
                    i += 1
                i += 1
            elif after == "O":
                i += 3
            else:
                i += 2  # an Alt or Option pair; a lone Esc at the end drops alone
            continue
        # 0x08 is Backspace on some terminals; LF is Return when cooked mode got there first.
        c = {"\x08": BACKSPACE, "\n": RETURN}.get(c, c)
        if c in NAMED or unicodedata.category(c) != "Cc":
            keys.append(c)
        i += 1
    return keys


def cells(c):
    """Terminal cells for one character: 0 for a combining mark, 2 for wide, else 1."""
    if unicodedata.combining(c) or unicodedata.category(c) in ("Mn", "Me"):
        return 0
    return 2 if unicodedata.east_asian_width(c) in ("W", "F") else 1


def rows(text, cols):
    """Rows the text occupies from column 0. A full row keeps the cursor on it."""
    if cols <= 0:
        return 1
    n, col = 1, 0
    for c in text:
        if c == "\n":  # cooked mode echoed a Return typed while the tool was starting
            n, col = n + 1, 0
            continue
        w = cells(c)
        if w and col and col + w > cols:
            n, col = n + 1, 0
        col += w
    return n


def cooked_echo(text):
    """What cooked mode showed for keys typed before raw mode: controls as ^X."""
    return "".join(
        "^" + chr(ord(c) ^ 0x40) if c != "\n" and unicodedata.category(c) == "Cc" else c
        for c in text
    )


def parse(argv):
    """Returns (width, flash, ring), or None for --help. Raises Usage."""
    width, flash, ring, seen = DEFAULT_WIDTH, False, False, False
    for arg in argv:
        if arg in ("-h", "--help"):
            return None
        if arg == "--flash":
            flash = True
        elif arg == "--ring":
            ring = True
        elif seen and arg.isascii() and arg.isdigit():
            raise Usage(f"margin: '{arg}' is a second width.")
        elif arg.isascii() and arg.isdigit() and int(arg) >= 1:
            width, seen = int(arg), True
        else:
            raise Usage(f"margin: '{arg}' is not a width.")
    return width, flash, ring


# The terminal layer.


def put(fd, text):
    data = text.encode("utf-8", "surrogateescape")
    while data:
        data = data[os.write(fd, data) :]


def columns(fd):
    try:
        return struct.unpack("HHHH", fcntl.ioctl(fd, termios.TIOCGWINSZ, bytes(8)))[1]
    except OSError:
        return 0


def repaint(fd, shown, buf):
    """Moves to the start of what is shown, clears to the end of the screen, writes buf."""
    up = rows(shown, columns(fd)) - 1
    return (f"\x1b[{up}A" if up else "") + "\r\x1b[J" + buf


def read_line(fd, width, flash):
    """The raw-mode loop. Returns (line or None, exit code)."""
    decode = codecs.getincrementaldecoder("utf-8")("surrogateescape").decode
    buf, lit = "", None  # lit: when the flash comes off, while the screen is inverted
    # Keys typed while uv and Python were starting are waiting already, echoed by cooked mode.
    ahead = bool(select.select([0], [], [], 0)[0])
    try:
        while True:
            if lit is not None and time.monotonic() >= lit:
                put(fd, FLASH_OFF)
                lit = None
            if not ahead:
                wait = None if lit is None else max(lit - time.monotonic(), 0)
                if not select.select([0], [], [], wait)[0]:
                    continue
            data = os.read(0, 4096)
            if not data:
                return None, 1
            text = decode(data)
            new, rang, end = buf, 0, None
            # ponytail: a new str per key; a 10,000 character paste takes under a second,
            # 100,000 about ten. A list buffer if pastes that size ever matter.
            for key in split_keys(text):
                if key in (RETURN, END, INTERRUPT):
                    end = key
                    break
                new, bells = press(new, key, width)
                rang |= bells
            if ahead:
                out = repaint(fd, cooked_echo(text), new)
            elif new.startswith(buf):
                out = new[len(buf) :]
            else:
                out = repaint(fd, buf, new)
            ahead, buf = False, new
            if rang and not flash:
                out += BEL
            elif rang and lit is None:
                out += FLASH_ON
                lit = time.monotonic() + FLASH_SECONDS
            if end == END and not buf:
                put(fd, out)
                return None, 1
            if end:
                if lit is not None:
                    out += FLASH_OFF
                    lit = None
                put(fd, out + "\r\n")
                return (None, 130) if end == INTERRUPT else (buf, 0)
            put(fd, out)
    finally:
        if lit is not None:
            put(fd, FLASH_OFF)


def ring_once(flash):
    try:
        fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
    except OSError:
        return 0
    try:
        put(fd, FLASH_ON if flash else BEL)
        if flash:
            time.sleep(FLASH_SECONDS)  # no keys are read here, so a plain sleep is fine
    finally:
        if flash:
            put(fd, FLASH_OFF)
        os.close(fd)
    if os.isatty(2):
        print(FOOTNOTE[flash], file=sys.stderr)
    return 0


def plain():
    """No terminal: one line from stdin to stdout, unchanged, and no ringing."""
    line = sys.stdin.buffer.readline()
    if not line:
        return 1
    sys.stdout.buffer.write(line if line.endswith(b"\n") else line + b"\n")
    return 0


def terminate(*_):
    """SIGTERM: leave through the finally blocks, which restore the terminal, once."""
    signal.signal(signal.SIGTERM, signal.SIG_IGN)
    sys.exit(143)


def main(argv):
    try:
        parsed = parse(argv)
    except Usage as e:
        print(e, file=sys.stderr)
        return 2
    if parsed is None:
        sys.stdout.write(HELP)
        return 0
    width, flash, ring = parsed
    signal.signal(signal.SIGTERM, terminate)
    if ring:
        return ring_once(flash)
    if not os.isatty(0):
        return plain()
    try:
        fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
    except OSError:
        return plain()
    saved = termios.tcgetattr(fd)
    try:
        tty.setraw(fd, termios.TCSANOW)  # never TCSAFLUSH: it would drop keys typed ahead
        line, code = read_line(fd, width, flash)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, saved)
        os.close(fd)
    if code == 130 and os.isatty(2):
        print("Line withdrawn.", file=sys.stderr)
    if line is not None:
        sys.stdout.buffer.write(line.encode("utf-8", "surrogateescape") + b"\n")
    return code


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except KeyboardInterrupt:  # Ctrl-C while the terminal was still cooked
        sys.exit(130)
