#!/usr/bin/env python3
"""
ACHOO 5 - a programming language made of sneezes, replies, blessings and apologies.

Every keyword, symbol, name, number and letter is a sneeze or a reply to one.
There are no brackets, no colons and no quotes. Under the hood it all decodes
to Python, so every Python feature, built-in function and standard library
module still works.

HOW IT WORKS
    Reply words         the most used code gets a word you'd say to a sneezer:
                        gesundheit is print, tissue is return, salud is if.
    World sneezes       achoo, atchoo, ahchoo, hachoo, hatchoo, aitchoo,
                        atishoo, kerchoo. The spelling picks a group and the
                        o's pick the item: acho is a space, achooo is "(",
                        atcho is "'". Never more than 9 o's.
    Spelled sneezes     ach + capital O's: one character in binary
                        (o = 0, O = 1). achOooOooo = 1001000 = "H".

    Each line of sneezes is one line of code.
    python3 achoo.py --sneezes lists every reply word and world sneeze.

THE RULES
    1. After every 7 statements, a line that says only  bless you.
       Forget it, or bless too early, and the program crashes.
    2. The last line must be  sorry everyone.
    3. Anything that is not a sneeze or a reply crashes.
    4. sniff starts a comment: the rest of that line can be normal words.
    5. Files end in .ach (old .achoo files work too). Other .ach files can be imported.

USAGE
    python3 achoo.py program.ach           run a program
    python3 achoo.py --sneezify prog.py    turn a Python file into ACHOO
    python3 achoo.py --python prog.ach     show the Python hidden in the sneezes
    python3 achoo.py --sneezes             list the reply words and world sneezes
"""
import builtins
import importlib.abc
import importlib.util
import io
import linecache
import os
import re
import sys
import tokenize
import traceback

PIECES = [
    " ", "    ", "(", ")", ".", ",", ":", "=", '"', "'",
    "self", "def", "return", "if", "else", "elif", "for", "in", "while", "import",
    "from", "class", "print", "__init__", "None", "True", "False", "and", "or", "not",
    "is", "try", "except", "finally", "with", "as", "lambda", "yield", "pass", "break",
    "continue", "raise", "global", "nonlocal", "del", "assert", "async", "await", "[", "]",
    "{", "}", "+", "-", "*", "/", "%", "==", "!=", "<",
    ">", "<=", ">=", "+=", "-=", "->", "**", "//", "#", "@",
    "_", "__name__", "__main__", "range", "len", "input", "str", "int", "\\", "match",
    "case", "f",
]
REPLIES = {
    "print": "gesundheit", "def": "cough", "return": "tissue", "if": "salud",
    "else": "sante", "elif": "salute", "for": "zdrowie", "while": "prosit",
    "self": "hanky", "import": "sniffle", "class": "fever", "True": "healthy",
    "False": "sick", "None": "snot",
}
STEMS = ["ach", "atch", "ahch", "hach", "hatch", "aitch", "atish", "kerch"]
PER_STEM = 9
WORD_FOR = dict(REPLIES)
for index, piece in enumerate(piece for piece in PIECES if piece not in REPLIES):
    WORD_FOR[piece] = STEMS[index // PER_STEM] + "o" * (index % PER_STEM + 1)
PIECE_FOR = {word: piece for piece, word in WORD_FOR.items()}
BLESSING = "bless you"
APOLOGY = "sorry everyone"
EXTENSIONS = (".ach", ".achoo")
PAUSE_FLAG = "--pause-on-crash"
COMMENT = "sniff"
LIMIT = 7
SPELLED = re.compile(r"achO[oO]*")
BY_LENGTH = sorted(PIECES, key=len, reverse=True)


class SneezeError(SyntaxError):
    pass


def sneeze_for(text):
    if text in WORD_FOR:
        return WORD_FOR[text]
    return "ach" + format(ord(text), "b").replace("0", "o").replace("1", "O")


def unsneeze(word, where):
    if word in PIECE_FOR:
        return PIECE_FOR[word]
    if SPELLED.fullmatch(word):
        return chr(int(word[3:].replace("o", "0").replace("O", "1"), 2))
    for stem in STEMS:
        stretch = word[len(stem):]
        if word.startswith(stem) and stretch and set(stretch) == {"o"}:
            if len(stretch) > PER_STEM:
                raise SneezeError(f"{where}: {len(stretch)} o's? nobody sneezes that hard")
            raise SneezeError(f"{where}: '{word}' doesn't mean anything yet")
    if re.fullmatch(r"ach[oO]+", word):
        raise SneezeError(f"{where}: '{word}' starts weakly. spelled sneezes start with a capital O")
    raise SneezeError(f"{where}: '{word}' is not a sneeze")


def encode_line(line):
    words, i = [], 0
    while i < len(line):
        for piece in BY_LENGTH:
            if line.startswith(piece, i):
                words.append(sneeze_for(piece))
                i += len(piece)
                break
        else:
            words.append(sneeze_for(line[i]))
            i += 1
    return " ".join(words)


def _statement_starts(source):
    starts, at_start = [], True
    skip = {tokenize.NL, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT,
            tokenize.ENCODING, tokenize.ENDMARKER}
    for tok in tokenize.generate_tokens(io.StringIO(source).readline):
        if tok.type in skip:
            continue
        if at_start:
            starts.append(tok.start[0])
            at_start = False
        if tok.type == tokenize.NEWLINE:
            at_start = True
    return starts


def translate(source, filename="<achoo>"):
    lines = source.split("\n")
    last = len(lines) - 1
    while last >= 0 and not lines[last].strip():
        last -= 1
    if last < 0 or " ".join(lines[last].split()).lower() != APOLOGY:
        raise SneezeError(f"{filename}: you sneezed on everyone and never apologised "
                          f"(the last line must be \"{APOLOGY}\")")

    python, blessings = [], []
    for number, line in enumerate(lines, start=1):
        text = line.strip()
        if number - 1 >= last:
            python.append("")
        elif " ".join(text.split()).lower() == BLESSING:
            blessings.append(number)
            python.append("")
        else:
            where = f"{filename}, line {number}"
            words = text.split()
            if COMMENT in words:
                words = words[:words.index(COMMENT)]
            python.append("".join(unsneeze(word, where) for word in words))
    code = "\n".join(python)

    try:
        starts = _statement_starts(code)
    except (tokenize.TokenError, SyntaxError) as e:
        raise SneezeError(f"{filename}: those sneezes don't make sense together: {e}")
    events = sorted([(r, 1, "bless") for r in blessings] + [(r, 0, "code") for r in starts])
    since = 0
    for row, _, kind in events:
        if kind == "bless":
            if since < LIMIT:
                raise SneezeError(f"{filename}, line {row}: blessed too early, "
                                  f"only {since} statement(s) since the last \"{BLESSING}\"")
            since = 0
        else:
            if since == LIMIT:
                raise SneezeError(f"{filename}, line {row}: nobody blessed me "
                                  f"(put a \"{BLESSING}\" line before this one)")
            since += 1
    return code


def _comments(source):
    found = {}
    for token in tokenize.generate_tokens(io.StringIO(source).readline):
        if token.type == tokenize.COMMENT:
            found[token.start[0]] = (token.start[1], token.string[1:].strip())
    return found


def sneezify(source):
    lines = source.split("\n")
    while lines and not lines[-1].strip():
        lines.pop()
    joined = "\n".join(lines)
    bless_before = set(_statement_starts(joined)[LIMIT::LIMIT])
    comments = _comments(joined)
    out = []
    for number, line in enumerate(lines, start=1):
        if number in bless_before:
            out.append(BLESSING)
        if number in comments:
            column, note = comments[number]
            code = encode_line(line[:column].rstrip())
            out.append(" ".join(part for part in (code, COMMENT, note) if part))
        else:
            out.append(encode_line(line))
    out.append(APOLOGY)
    return "\n".join(out) + "\n"


def compile_achoo(path):
    with open(path, encoding="utf-8") as f:
        code = translate(f.read(), path)
    lines = [line + "\n" for line in code.split("\n")]
    linecache.cache[path] = (len(code), None, lines, path)
    try:
        return compile(code, path, "exec")
    except SyntaxError as e:
        if e.lineno and e.lineno <= len(lines):
            e.text = lines[e.lineno - 1]
        raise


class AchooFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader):
    def find_spec(self, name, path, target=None):
        leaf = name.rpartition(".")[2]
        for folder in (path or sys.path):
            folder = folder or "."
            for extension in EXTENSIONS:
                file = os.path.join(folder, leaf + extension)
                if os.path.isfile(file):
                    return importlib.util.spec_from_file_location(name, file, loader=self)
                package = os.path.join(folder, leaf, "__init__" + extension)
                if os.path.isfile(package):
                    return importlib.util.spec_from_file_location(
                        name, package, loader=self,
                        submodule_search_locations=[os.path.join(folder, leaf)])
        return None

    def create_module(self, spec):
        return None

    def exec_module(self, module):
        exec(compile_achoo(module.__spec__.origin), module.__dict__)


def run(path, argv=()):
    if not path.endswith(EXTENSIONS):
        raise SneezeError(f"{path}: that file isn't a tissue. use .ach")
    if not any(isinstance(f, AchooFinder) for f in sys.meta_path):
        sys.meta_path.insert(0, AchooFinder())
    code = compile_achoo(path)
    sys.argv = [path, *argv]
    sys.path[0] = os.path.dirname(os.path.abspath(path))
    exec(code, {"__name__": "__main__", "__file__": path, "__builtins__": builtins})


def wait_for_enter():
    try:
        input("\nPress Enter to close...")
    except EOFError:
        pass


def crash(message, pause):
    if not pause:
        sys.exit(message)
    print(message, file=sys.stderr)
    wait_for_enter()
    sys.exit(1)


def main():
    pause = PAUSE_FLAG in sys.argv[1:]
    args = [arg for arg in sys.argv[1:] if arg != PAUSE_FLAG]
    try:
        if not args:
            sys.exit(__doc__)
        if args[0] == "--sneezes":
            for piece in PIECES:
                print(f"{WORD_FOR[piece]:<14} {piece!r}")
            print("\nanything else: ach + the character code in binary, o = 0, O = 1")
        elif args[0] == "--python" and len(args) == 2:
            with open(args[1], encoding="utf-8") as f:
                print(translate(f.read(), args[1]))
        elif args[0] == "--sneezify" and len(args) == 2:
            with open(args[1], encoding="utf-8") as f:
                sys.stdout.write(sneezify(f.read()))
        else:
            run(args[0], args[1:])
    except SneezeError as e:
        crash(f"SneezeError: {e.msg if getattr(e, 'msg', None) else e}", pause)
    except Exception as e:
        tb, here = e.__traceback__, os.path.abspath(__file__)
        while tb is not None and os.path.abspath(tb.tb_frame.f_code.co_filename) == here:
            tb = tb.tb_next
        sys.stderr.write(f"Your program caught a {type(e).__name__}. achoo.\n")
        traceback.print_exception(type(e), e, tb)
        if pause:
            wait_for_enter()
        sys.exit(1)


if __name__ == "__main__":
    main()
