import sys
from dataclasses import dataclass, field

from itertools import chain

DEBUG = True
debug_padding = 24

def debug_print(printname, *args):
    if DEBUG:
        print(f"{'DEBUG::'+printname:<{debug_padding}}", *args)

@dataclass
class RangeContainer:
    dest_start: int = 0
    src_start: int = 0
    range: int = 0


@dataclass
class Seed:
    number: int = 0
    soil: int = 0
    fertilizer: int = 0
    water: int = 0
    light: int = 0
    temperature: int = 0
    humidity: int = 0
    location: int = 0


seeds = []
transforms = []

def map_range(num, map_ranges):

    for range_cont in map_ranges:
        if num >= range_cont.src_start and num <= range_cont.src_start+range_cont.range:
            debug_print("in range", num, range_cont)
            return (num-range_cont.src_start) + range_cont.dest_start
    return num


print("Parsing Input:")
print("")
print("===================================\n");

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

parse_map_no = 0    #the index of the maps that we are processing
                    # 1 is seed-to-soil
                    # 2 is soil-to-fert
                    # and so on

#for line in sys.stdin:
for line in f.readlines():
    line = line.strip()
    debug_print("input",  line, "no", parse_map_no)
    if line == "":
        continue
    if line[:7] == "seeds: ":
        seeds = [Seed(int(num)) for num in line[7:].split()]
        debug_print("seeds", [s.number for s in seeds])
        continue
    if "map" in line:
        parse_map_no += 1
        transforms.append([])
        continue
    
    pr = [int(x) for x in line.split()]
    transforms[-1].append(RangeContainer(pr[0], pr[1], pr[2]))
    #debug_print("transforms", transforms[-1])

print("")
print(" Proccessing:")
print("===================================\n");
# Insert Processing Code

for seed in seeds:
    attributes = seed.__dir__()[:8]
    for i, attribute in enumerate(attributes):
        if i == 0: continue
        setattr(seed, attribute, map_range(getattr(seed, attributes[i-1]), transforms[i-1]))
        debug_print("attr", i , attribute)
        debug_print("set_val", i , getattr(seed, attribute))
    seed.soil = map_range(seed.number, transforms[0])
    debug_print("soil", seed.soil)
    #for i, attribute in  enumerate(attributes):
    #    setattr(seed, attribute, map_range(seed, transforms[i-1]))
    #    debug_print("get", attribute, getattr(seed, attribute))
    #debug_print(f"seed {seed.number}, soil {seed.soil}, fertilizer {seed.fertilizer}")

for seed in seeds:
    debug_print("location", seed.location)



print("")
print(" Calculate Answer:")
print("===================================\n");


min_location = min([s.location for s in seeds])




print("")
print(" Answer:")
print("===================================\n");
print(f"min_location: \n{min_location}");