BLOCK_OPENERS = {
    "START_RACE": "def",
    "CHECKPOINT": "if",
    "ALT_ROUTE": "elif",
    "ELSE_ROUTE": "else",
    "LOOP_TRACK": "while",
    "LAP": "for",
}

SIMPLE_KEYWORDS = {
    "CHAT": "print",
    "PB": "",
    "GO": "",
    "RESTART_MAP": "return",
    "DNF": "break",
    "RESET_RUN": "continue",
}

OPERATORS = {
    "FASTER_THAN": ">",
    "SLOWER_THAN": "<",
    "EQUALS": "==",
    "NOT_PB": "!=",
    "AT_LEAST": ">=",
    "AT_MOST": "<=",
}


def translate(source: str) -> str:
    indent = 0
    output = []

    for raw_line in source.splitlines():
        line = raw_line.strip()

        if not line:
            continue

        if line == "FINISH":
            indent -= 1
            if indent < 0:
                raise SyntaxError("FINISH without matching block")
            continue

        for k, v in OPERATORS.items():
            line = line.replace(k, v)

        for k, v in SIMPLE_KEYWORDS.items():
            if line.startswith(k + " "):
                line = line.replace(k, v, 1)

        opened = False
        for k, v in BLOCK_OPENERS.items():
            if line.startswith(k):
                rest = line[len(k):].strip()
                line = f"{v} {rest}:".rstrip()
                output.append("    " * indent + line)
                indent += 1
                opened = True
                break

        if not opened:
            output.append("    " * indent + line)

    if indent != 0:
        raise SyntaxError("Unclosed block (missing FINISH)")

    return "\n".join(output)
