import sys
import os
sys.path.insert(1, os.path.abspath('../../'))
from python_tools.aoc_utils import *


L = []

def part_one(input):
    p1 = 0
    empty = False
    id = 0
    for i in input:
        if empty:
            L.extend(int(i)*['.'])
        else:
            L.extend(int(i)*[id])
            id = (id + 1)
        empty = not empty
    idx = 0
    while(idx < len(L)):
        if L[idx] == '.':
            end = L.pop()
            while end == '.' and idx<len(L)-1:
                end = L.pop()
            L[idx] = end
        if L[idx] != '.':
            p1 += idx * L[idx]
        idx+=1
    print("Part One: ", p1)

L2 = []

def part_two(input):
    p2 = 0
    empty = False
    id = 0
    for i in input:
        if empty:
            L2.append(int(i)*['.'])
        else:
            L2.append(int(i)*[id])
            id = (id + 1)
        empty = not empty
    idx = 0
    while(idx < len(L2)):
        end_idx = -1
        while L2[idx].count('.') > 0:
            if len(L2)+end_idx < idx + 1:
                break
            elif L2[end_idx].count('.') == 0:
                if len(L2[end_idx]) <= L2[idx].count('.'):
                    temp = L2[end_idx]
                    for c, i in enumerate(temp):
                        L2[idx][L2[idx].index('.')] = i
                        L2[end_idx][c] = '.'

            end_idx -= 1
        idx+=1

    Flat_L2 = [j for i in L2 for j in i]
    for count, i in enumerate(Flat_L2):
        if i != '.':
            p2 += count*i
    print("Part Two: ", p2)


def main():
    f = open('input.txt', 'r')
    contents = f.read().strip()

    part_one(contents)
    part_two(contents)

if __name__ == "__main__":
    main()