#!/usr/bin/env python3
# braille - text to Braille unicode and back
# Usage: braille TEXT... | braille --decode BRAILLE... | braille --file FILE
#   Grade-1 Braille: a-z, digits (with number sign ⠼), space, and . , ? ! ' -.
#   Input may also come from stdin.
import argparse, sys

# Braille patterns as 6-dot bit strings (dots 1-2-3-4-5-6 -> bits 0-5)
DOTS = {
    "a": "100000", "b": "110000", "c": "100100", "d": "100110", "e": "100010",
    "f": "110100", "g": "110110", "h": "110010", "i": "010100", "j": "010110",
    "k": "101000", "l": "111000", "m": "101100", "n": "101110", "o": "101010",
    "p": "111100", "q": "111110", "r": "111010", "s": "011100", "t": "011110",
    "u": "101001", "v": "111001", "w": "010111", "x": "101101", "y": "101111",
    "z": "101011", " ": "000000",
    ".": "010011", ",": "010000", "?": "011001", "!": "011010",
    "'": "001000", "-": "001001", "/": "001100",
}
NUM_SIGN = "001111"  # ⠼ precedes digits; digits reuse a-j
DIGITS = {"1": "a", "2": "b", "3": "c", "4": "d", "5": "e",
          "6": "f", "7": "g", "8": "h", "9": "i", "0": "j"}

def dots_to_char(bits):
    cp = 0x2800
    for i, b in enumerate(bits):
        if b == "1":
            cp |= 1 << i
    return chr(cp)

def char_to_dots(ch):
    cp = ord(ch) - 0x2800
    return "".join("1" if cp & (1 << i) else "0" for i in range(6))

BRAILLE = {k: dots_to_char(v) for k, v in DOTS.items()}
BRAILLE[NUM_SIGN] = dots_to_char(NUM_SIGN)
REV = {v: k for k, v in BRAILLE.items()}

def encode(text):
    out = []
    in_num = False
    for ch in text.lower():
        if ch.isdigit():
            if not in_num:
                out.append(dots_to_char(NUM_SIGN))
                in_num = True
            out.append(BRAILLE[DIGITS[ch]])
        else:
            in_num = False
            out.append(BRAILLE.get(ch, "?"))
    return "".join(out)

def decode(text):
    out = []
    in_num = False
    for ch in text:
        if ch == dots_to_char(NUM_SIGN):
            in_num = True
            continue
        letter = REV.get(ch, "?")
        if in_num and letter in "abcdefghij":
            out.append("1234567890"["abcdefghij".index(letter)])
        else:
            in_num = False
            out.append(letter)
    return "".join(out)

def selftest():
    assert encode("a") == "⠁" and encode("z") == "⠵"
    assert decode(encode("hello world")) == "hello world"
    assert decode(encode("call 911")) == "call 911"
    assert encode("SOS".lower()) == "⠎⠕⠎"
    print("braille selftest: ok (a/z cells, hello world, digits with number sign)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="braille",
        description="Text to Braille unicode and back (Grade-1).")
    p.add_argument("text", nargs="*", help="text to encode (or Braille to decode with --decode)")
    p.add_argument("--decode", "-d", action="store_true", help="decode Braille to text")
    p.add_argument("--file", "-f", help="read input from FILE instead of arguments")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.file:
        try:
            data = open(a.file, encoding="utf-8").read()
        except OSError as e:
            print(f"braille: {e}", file=sys.stderr); return 2
    elif a.text:
        data = " ".join(a.text)
    elif not sys.stdin.isatty():
        data = sys.stdin.read()
    else:
        p.error("give TEXT, --file, or pipe input on stdin")
    data = data.strip("\n")
    print(decode(data) if a.decode else encode(data))
    return 0

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