#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from copy import deepcopy
from time import time


start_time = time()

ex_p1_input = """Register A: 729
Register B: 0
Register C: 0
Program: 0,1,5,4,3,0
"""

ex_p2_input = """Register A: 2024
Register B: 0
Register C: 0
Program: 0,3,5,4,3,0
"""

real_input = """Register A: 25358015
Register B: 0
Register C: 0
Program: 2,4,1,1,7,5,0,3,4,7,1,6,5,5,3,0
"""

real_erik = """Register A: 25358015
Register B: 0
Register C: 0
Program: 2,4,1,2,7,5,4,5,1,3,5,5,0,3,3,0
"""

def read_input(input_var:str)->list[int]:
    inp = input_var.split("\n")
    program = list(map(int, inp[3].split(':')[1].split(",")))
    return program

def do(instruction:int, operand:int, point:int):
    global ra, rb, rc, out
    if operand in [0, 1, 2, 3]:
        ope = operand
    elif operand == 4:
        ope = ra
    elif operand == 5:
        ope = rb
    elif operand == 6:
        ope = rc
    match instruction:
        case 0:
            ra = int(ra/(2**ope))
        case 1:
            rb = rb ^ operand
        case 2:
            rb = ope % 8
        case 3:
            if ra != 0:
                point = ope-2
        case 4:
            rb = rb ^ rc
        case 5:
            #print(ra,rb,rc,ope,ope%8)
            out.append(ope%8)
        case 6:
            rb = int(ra/(2**ope))
        case 7:
            rc = int(ra/(2**ope))
        case _:
            pass
    return point

if __name__ == "__main__":
    #prog = read_input(ex_p1_input)
    prog = read_input(ex_p2_input)
    #prog = read_input(real_input)
    #prog = read_input(real_erik)
    count = 0
    sol_list = [""]
    for x in range(2,len(prog)+2,2):
        new_list = []
        for i in sol_list:
            for o1 in range(8):
                for o2 in range(8):
                    count += 1
                    i_str=f"{i}{o1}{o2}"
                    ra_a = int(i_str, 8)
                    ra = int(i_str, 8)
                    rc, rb = 0, 0
                    out = []
                    pointer = 0
                    while pointer < len(prog):
                        pointer = do(prog[pointer], prog[pointer+1], pointer)
                        pointer += 2
                    # Program: 2,4,1,1,7,5,0,3,4,7,1,6,5,5,3,0
                    if len(out) == x and out[-x:] == prog[-x:]:
                        new_list.append(f"{ra_a:o}")
                        #print(f"Prog: {prog}")
                        print(f"dec:{ra_a}, oct:{ra_a:o}, out:{out}")
        sol_list = deepcopy(new_list)
    integer_liste = [int(number, 8) for number in sol_list]
    print()
    print(f"Prog: {prog}")
    print(f"Solution Part2: {min(integer_liste)}")
    print(f"Checked Numbers: {count}")
    print(f'Runtime: {time()-start_time:.5f} s')
