from dis import Instruction
import re
from tabnanny import check
import numpy as np
import copy

file = open('input.txt', 'r')
# file = open('test.txt', 'r')
content = file.read()
# lines = content.splitlines()
paragraphs = content.split("\n\n")
sum = 0

flows =  {}

print(paragraphs[0].split("\n")[0].split('{')[1].strip("}"))
for workflow in paragraphs[0].split("\n"):
    sub_workflow = workflow.split('{')
    name = sub_workflow[0]
    instructions = sub_workflow[1].strip("}").split(",")
    # print(instructions)
    inst_list = []
    for a in instructions:
        if_stat = a.split(":")
        logic = []
        for ch in ["<", ">"]:
            if ch in if_stat[0]:
                temp = if_stat[0].split(ch)
                logic = [temp[0], ch, int(temp[1])]
                break
        # inst
        inst_list.append(logic+[if_stat[-1]])
    print(inst_list)


    flows[name] = inst_list

vals = []

for val in paragraphs[1].split("\n"):
    current_val = {}
    for i in val.strip("{}").split(","):
        x = i.split("=")
        print(x)
        current_val[x[0]] = int(x[1])
    vals.append(current_val)

print(vals)


print(flows)

sum = 0

Possible = {
    "x": {"min": 1, "max":4000},
    "m": {"min": 1, "max":4000},
    "a": {"min": 1, "max":4000},
    "s": {"min": 1, "max":4000},
    "keys": [],
}

total_list = []

def f(key, possible_in):
    
    possible = copy.deepcopy(possible_in)
    possible["keys"].append(key)
    if key == "A":
        total_list.append(possible)
    elif key != "R":
        for inst in flows[key]:
            new_possible = copy.deepcopy(possible)
            if len(inst) == 1:
                f(inst[-1], possible)
                break
            else:
                if inst[1] == "<":
                    new_possible[inst[0]]["max"] = min(inst[2]-1, new_possible[inst[0]]["max"])
                    f(inst[-1], new_possible)
                    possible[inst[0]]["min"] = max(inst[2], possible[inst[0]]["min"])
                elif inst[1] == ">":
                    new_possible[inst[0]]["min"] = max(inst[2]+1, new_possible[inst[0]]["min"])
                    f(inst[-1], new_possible)
                    possible[inst[0]]["max"] = min(inst[2], possible[inst[0]]["max"])
                else:
                    print("PANIC!")



key = "in"
f(key, Possible)

print(total_list)

for entry in total_list:
    temp = 1
    for ch in ['x', 'm', 'a', 's']:
        temp *= max(0, entry[ch]["max"]-entry[ch]["min"]+1)
    sum += temp

print(sum)

file.close()