from MaMaGUI import MaMaGUI
from MaMa import MaMa

if __name__ == "__main__":
    # Algor
    prog = [
        'ldo(-1)',
        'ldo(-1)',
        'equal(25)',
        'ldo(0)',
        'ldo(-2)',
        'leq(11)',
        'ldo(0)',
        'ldo(-2)',
        'sub',
        'sto(-1)',
        'ujp(15)',
        'ldo(-1)',
        'ldo(-1)',
        'sub',
        'sto(-2)',
        'ldo(-1)',
        'push(0)',
        'equal(19)',
        'ujp(3)',
        'ldo(-1)',
        'ldo(-1)',
        'sto(-3)',
        'sto(-1)',
        'pop',
        'stop',
        'pop',
        'stop'
    ]

    # Test cases
    tests = [
        (4,6,2),
        (10,5,5),
        (9,3,3),
        (21,14,7),
        (7,13,1),
        (12,18,6),
        (25,5,5),
        (42,56,14),
        (100,80,20),
        (81,27,27)
    ]

    # Print restults into console
    passed = 0
    for a,b,expected in tests:
        m = MaMa(prog, [a,b])
        m.run()
        result = m.stack.get(0)
        if result == expected:
            print(f"GGT({a},{b}) = {result} ✓")
            passed += 1
        else:
            print(f"GGT({a},{b}) = {result} ✗ expected {expected}")
    print(f"{passed}/{len(tests)} tests passed.")

    # Load machine
    machine = MaMa(prog, [4, 6])
    journal = machine.run()

    with open("run.txt", "w") as f:
        i = 1
        for step in journal:
            s = step["p_stack"]
            p = step["p_prog"]
            S = tuple(step["stack"].values())
            f.write(f"{i}: ({s},{p},{S})\n")
            i += 1

    # Visualize finished execution using journal
    machine = MaMa(prog, [4, 6])
    gui = MaMaGUI(machine)
    gui.display()
