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

# works for example but not for puzzle-input


#file = "./input.txt"
file = "./ex2.txt"
#file = "./ex1.txt"
from time import time

start_time = time()

def input_to_list(input_str:str) -> list[list[int]]:
    out = []
    idx = 0
    for i in range(0,len(input_str),2):
        try:
            out.append([idx,int(input_str[i]),int(input_str[i+1])])
        except IndexError:
            out.append([idx,int(input_str[i]), 0])
        idx +=1
    return out

def de_frag(il:list[list[int]]) -> list[list[int]]:
    for i in range(len(il)-1, 0, -1):
        for j in range(len(il)):
            if il[j][2] == 0:
                continue
            if j >= i:
                break
            if il[j][2] >= il[i][1]:
                #print(il[j],il[j+1],il[i], end=" ----> ")
                tjf = il[j][2]
 #               tjl = il[j][1]
                tif = il[i][2]
                til = il[i][1]
                il.insert(j+1, il.pop(i))
                il[j][2] = 0
                il[j+1][2] = tjf-til
                il[i][2] += til+tif
                #print(il[j],il[j+1],il[i])
                #print(il)
    return il

def checksum(il:list[list[int]]) -> int:
    result = 0
    idx = 0
    for i in range(len(il)):
        for _ in range(il[i][1]):
            result += idx * il[i][0]
            idx +=1
        idx += il[i][2]
    return result

if __name__ == "__main__":
    input_string = ""
    input_file = open(file, "r")
    for line in input_file:
        line = line.strip()
        if line == "":
            continue
        input_string += line
    input_file.close()

    ex = input_to_list(input_string)
    #print(ex)
    de = de_frag(ex)
    print(de)
    sol = checksum(de)
    print(f'Solution: {sol}')
    print(f'Runtime: {time()-start_time:.2f} s')