#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# like in: https://www.reddit.com/r/adventofcode/comments/1hd7irq/2024_day_13_an_explanation_of_the_mathematics/

file = "./input.txt"
#file = "./ex.txt"
from time import time
import re
start_time = time()

def check_machine(m:dict) -> int:
    a = (m['p_x']*m["bb_y"] - m["p_y"]*m["bb_x"]) / (m["ba_x"]*m["bb_y"] - m["ba_y"]*m["bb_x"])
    b = (m["ba_x"]*m["p_y"] - m["ba_y"]*m["p_x"]) / (m["ba_x"]*m["bb_y"] - m["ba_y"]*m["bb_x"])
    if (a*10)%10==0 and (b*10)%10==0:
        return int((3*a)+b)
    else:
        return 0


if __name__ == "__main__":
    input_dict = {}
    m_count = 0
    input_file = open(file, "r")
    for line in input_file:
        line = line.strip()
        if line == "":
            continue
        if 'Button A' in line:
            pat_b_a = r'A\: X\+(\d+), Y\+(\d+)'
            match = re.search(pat_b_a, line)
            input_dict[f'M_{m_count}'] = {'ba_x' :int(match.group(1))}
            input_dict[f'M_{m_count}']['ba_y'] = int(match.group(2))
        elif 'Button B' in line:
            pat_b_b = r'B\: X\+(\d+), Y\+(\d+)'
            match = re.search(pat_b_b, line)
            input_dict[f'M_{m_count}']['bb_x'] = int(match.group(1))
            input_dict[f'M_{m_count}']['bb_y'] = int(match.group(2))
        elif 'Prize' in line:
            pat_p = r'Prize\: X\=(\d+), Y\=(\d+)'
            match = re.search(pat_p, line)
            input_dict[f'M_{m_count}']['p_x'] = int(match.group(1)) +10000000000000
            input_dict[f'M_{m_count}']['p_y'] = int(match.group(2)) +10000000000000
            m_count += 1
    input_file.close()

    solution = 0
    for key in input_dict.keys():
        tok = check_machine(input_dict[key])
        print(key, tok)
        solution +=tok

    #print(input_dict)
    print(f'Solution: {solution}')
    print(f'Runtime: {time()-start_time:.2f} s')