import shared

def get_sequence(values):
    differences = []
    for idx in range(len(values)-1):
        x1, x2 = values[idx:idx+2]
        differences.append(x2 - x1)
    return differences

def print_pretty(history):
    for idx, h in enumerate(history):
        print(("  " * idx) + "  ".join(map(str, h)))

def calculate_new_value(row1, row2):
    print(row1, row2)


# @shared.profile
def part1(rows):
    # gather
    history = [[shared.spl(row.split())] for row in rows]
    for h in history:
        vals = h[0]
        while True:
            vals = get_sequence(vals)
            h.append(vals)
            if shared.all_equal(vals) and vals[0] == 0:
                break
    # do calcs
    for h in history:
        h[-1].append(0)
        for idx in range(1, len(h)):
            i = (idx * -1) -1
            me = h[i]
            above = h[i+1]
            #print(above,me)
            new_val = me[-1] + above[-1]
            h[i].append(new_val)

    # totals
    newest = [x[0][-1] for x in history]
    print(sum(newest))




# @shared.profile
def part2(rows):
    # gather
    history = [[shared.spl(row.split())] for row in rows]
    for h in history:
        vals = h[0]
        while True:
            vals = get_sequence(vals)
            h.append(vals)
            if shared.all_equal(vals) and vals[0] == 0:
                break
    # do calcs
    for h in history:
        h[-1].insert(0, 0)
        for idx in range(1, len(h)):
            i = (idx * -1) -1
            me = h[i]
            below = h[i+1]
            new_val = me[0] - below[0]

            h[i].insert(0, new_val)
    # totals
    newest = [x[0][0] for x in history]
    print(sum(newest))




def main():
    rows = [row for row in shared.load_rows(9)]
    with shared.elapsed_timer() as elapsed:
        part1(rows)
        print("🕒", elapsed())

    rows = [row for row in shared.load_rows(9, True)]
    with shared.elapsed_timer() as elapsed:
        part2(rows)
        print("🕒", elapsed())


if __name__ == "__main__":
    main()
