import sys
import copy
import string
from dataclasses import dataclass

DEBUG = True
padding=40

def debug_print(printname, *args):
    if not DEBUG:
        return
    print(f"{'DEBUG::'+printname:<{padding}}", *args)
    pass


FILENAME = "/home/icaema/Public/advent-of-code/day-03/data/p01data.txt"
f = open(FILENAME, "r")



engine = [];
parts = [];
part_numbers = [];



def hasNumber(part):
    window = \
    [[[-1,-1],[0,-1],[1,-1]],
     [[-1, 0],[0, 0],[1, 0]],
     [[-1, 1],[0, 1],[1, 1]]]
    for w_y in window:
        for transform in w_y:
                has_no=False
                transformed_x = part['x'] + transform[0]
                transformed_y = part['y'] + transform[1]
                debug_print("hasNumber::check_location", f"part==[{part['x']}, {part['y']}];  engine[{transformed_x}, {transformed_y}] == {engine[transformed_y][transformed_x]}")
                if engine[transformed_y][transformed_x].isdigit():
                    part['has_number'] = True
                #if engine[part.w_x][]
                #debug_print("aaaaa not matricies", f"part=[{part['x']},{part['y']}] x:", engine)
                pass

def numberIsPartOfPart(part_number):
    window = \
    [[[-1,-1],[0,-1],[1,-1]],
     [[-1, 0],[0, 0],[1, 0]],
     [[-1, 1],[0, 1],[1, 1]]]
    
    for digit in part_number['locations']:
        for w_y in window:
            for transform in w_y:
                transformed_x = digit['x'] + transform[0]
                transformed_y = digit['y'] + transform[1]
                if transformed_y < 0 or transformed_y >= len(engine):
                    continue
                if transformed_x < 0 or transformed_x >= len(engine[transformed_y]):
                    continue
                debug_print("numberIsPartOfPart", f"letter {digit['digit']} point [{transformed_x}, {transformed_y}] is a valid coord. contains: {engine[transformed_y][transformed_x]}")
                if engine[transformed_y][transformed_x] != '.' and not engine[transformed_y][transformed_x].isdigit():
                    debug_print("numberIsPartOfPart", f"Number is part of part")
                    part_number['is_part_of_part'] = True
                pass
        pass
    pass




debug_print("Parse Input")
#========INPUT PARSE==========
#for line in sys.stdin:
for line in f.readlines():
    line = line.strip()
    debug_print("input",  line)
    engine.append(line)

debug_print("engine")
# https://stackoverflow.com/questions/17870612/printing-a-two-dimensional-array-in-python
print('\n'.join([''.join(['{:1}'.format(item) for item in row]) 
      for row in engine]))
#=============================


empty_partno = {
    'is_part_of_part': False,
    'ascii': "",
    'gen_int': False,
    'integer': 0,
    'locations': []
}

#=====Extract Part Numbers=====
debug_print("Extract Part Numbers")

current_parsing_part_number = copy.deepcopy(empty_partno)
for y in range(len(engine)):
    for x in range(len(engine[y])):
        if engine[y][x].isdigit():
            current_parsing_part_number['ascii'] += engine[y][x]
            current_parsing_part_number['locations'].append({'digit':engine[y][x], 'x':x, 'y':y})
        else:
            if current_parsing_part_number['ascii'] == "":
                continue
            debug_print("PARTNOEXT", f"found complete part number: {current_parsing_part_number['ascii'].rjust(4)}, locations: {current_parsing_part_number['locations']}")
            current_parsing_part_number['integer'] = int(current_parsing_part_number['ascii'])
            current_parsing_part_number['gen_int'] = True
            part_numbers.append(current_parsing_part_number)
            current_parsing_part_number = copy.deepcopy(empty_partno)
            numberIsPartOfPart(part_numbers[-1])
            pass
        pass

#==============================



debug_print("Extract Parts")
for y in range(len(engine)):
    for x in range(len(engine[y])):
        #debug_print("slot ",f"x:{x}, y:{y}", engine[y][x])
        if engine[y][x] == '.' or engine[y][x].isdigit():
            continue
        else:
            parts.append({'x':x,'y':y, 'symbol':engine[y][x], 'has_number':False})
            debug_print("Found Part", f"{parts[-1]}")
            #hasNumber(parts[-1])


# Insert Processing Code



for part_number in part_numbers:
    debug_print("part_number print", part_number)






parts_that_are_attached_to_parts = [part_number['integer'] for part_number in part_numbers if part_number['is_part_of_part'] == True]

print(parts_that_are_attached_to_parts)



print("")
print("Processed:")
print("")
print("===================================\n");
print("parts_that_are_attached_to_parts")
print(f"Answer: \n{sum(parts_that_are_attached_to_parts)}");