import sys
import re

class TonyPytony:
    """
    Motore di esecuzione per il linguaggio TonyPytony.
    Gestisce variabili, espressioni e output.
    """

    def __init__(self):
        self.variables = {}

    def run_line(self, line):
        line = line.strip()
        if not line or line.startswith("//"):
            return

        # Comando 'urla' (Print)
        if line.startswith("urla "):
            val = line[5:].strip()
            print(self.get_value(val))

        # Comando 'bomboroide' (Assegnazione)
        elif line.startswith("bomboroide "):
            match = re.match(r"bomboroide (.+) = (.+)", line)
            if match:
                var_name, var_expr = match.groups()
                self.variables[var_name.strip()] = self.evaluate_expression(var_expr.strip())

    def get_value(self, token):
        token = token.strip()
        if token.startswith('"') and token.endswith('"'):
            return token[1:-1]
        if token.isdigit():
            return int(token)
        return self.variables.get(token, f"Runtime Error: {token} non definito.")

    def evaluate_expression(self, expr):
        # Operatore 'movimento' (Addizione/Concatenazione)
        if " movimento " in expr:
            parts = expr.split(" movimento ")
            val1 = self.get_value(parts[0])
            val2 = self.get_value(parts[1])
            try:
                return val1 + val2
            except TypeError:
                return f"Runtime Error: Tipi incompatibili per 'movimento'"
        return self.get_value(expr)

def main():
    if len(sys.argv) < 2:
        print("TonyPytony Engine v0.1.0")
        print("Utilizzo: tony <file.ptny>")
        return

    interpreter = TonyPytony()
    try:
        with open(sys.argv[1], "r", encoding="utf-8") as file:
            for line in file:
                interpreter.run_line(line)
    except Exception as e:
        print(f"Errore critico: {e}")

if __name__ == "__main__":
    main()