from pprint import pprint as pp
from pathlib import Path
import json
from shared import load_rows
import re

from functools import reduce
import operator

PWD = []
FS = {"/": {".": {"size": 0, "files": []}}}


def get_keys(input_dict):
    for key, value in input_dict.items():
        if isinstance(value, dict):
            for subkey in get_keys(value):
                yield key + "," + subkey
        else:
            if key in ("files"):
                continue
            yield f"{value}"


def getFromDict(mapList):
    return reduce(operator.getitem, mapList, FS)


def setInDict(mapList, value):
    getFromDict(mapList[:-1])[mapList[-1]] = value


def addInDict(mapList, filename, value):
    try:
        v = getFromDict(mapList[:-1])[mapList[-1]]
        v += value
        getFromDict(mapList[:-1])[mapList[-1]] = v
    except KeyError:
        getFromDict(mapList[:-1])["."] = {"size": 0, "files": []}
        v = getFromDict(mapList[:-1])[mapList[-1]]
        v["size"] += 0  # Value
        v["files"].append(f"{filename}:{value}")
        getFromDict(mapList[:-1])[mapList[-1]] = v
    except TypeError:
        v = getFromDict(mapList[:-1])["."]
        v["size"] += 0  # value
        v["files"].append(f"{filename}:{value}")
        getFromDict(mapList[:-1])[mapList[-1]] = v


def part1(rows):
    build_fs(rows)
    # calculate_directories()


def calculate_directories():
    keys = list(get_keys(FS))
    new_FS = {}
    for key in keys:
        pwd = key.split(",")
        size = int(pwd.pop())  # split out size
        pwd.pop()  # remove .
        pwd_key = ",".join(pwd)
        parent = ",".join(pwd[:-1])
        new_FS[pwd_key] = {"size": size, "full_size": size, "parent": parent}
    print("made")

    # pp(new_FS)
    # print("----")
    # for pwd, directory in new_FS.items():
    #    print(pwd, "\t", directory['parent'])
    print(new_FS.keys())
    print("keys^")
    for pwd, directory in new_FS.items():
        parent = directory["parent"]
        if parent:
            print(parent)
            # print(f"{pwd}:{parent} Adding {directory['size']} to fullsize {new_FS[parent]['full_size']}")
            new_FS[parent]["size"] += directory["size"]
    print("added sizes")

    sizes = []
    for k, v in new_FS.items():
        sizes.append(v["size"])
    total = 0

    for size in sizes:
        if size <= 100000:
            print("+", size)
            total += size

    print("=", total)


def build_fs(rows):
    LS_ING = False
    for row in rows:
        parts = row.split(" ")
        if parts[0] == "$":
            if LS_ING:
                LS_ING = False

            # Action
            if parts[1] == "cd":
                if parts[2] == "..":
                    PWD.pop()
                else:
                    PWD.append(parts[2])
                # print(PWD)
            elif parts[1] == "ls":
                LS_ING = True
            continue
        if LS_ING:
            if parts[0] == "dir":
                add_directory(parts[1])
            else:
                add_file(parts[1], int(parts[0]))
    jp(FS)


def jp(d):
    output = json.dumps(FS, indent=4)
    output2 = re.sub(r'": \[\s+', '": [', output)
    output3 = re.sub(r'",\s+', '", ', output2)
    output4 = re.sub(r'"\s+\]', '"]', output3)
    print(output4)


def add_directory(dirname):
    temp_new_path = PWD + [dirname]
    setInDict(temp_new_path, {".": {"size": 0, "files": []}})


def add_file(filename, size):
    # print(".", PWD, filename, size)
    mapList = PWD + ["."]
    addInDict(mapList, filename, size)
    curr = getFromDict(mapList[:-1])
    print(curr)
    # print(curr)
    s = curr["."]
    s["size"] += size
    print(size, s)
    tmp = mapList + ["size"]
    setInDict(mapList, s)
    print("-----")


def part2(row):
    pass


def main():
    rows = load_rows(7)
    part1(rows)
    part2(rows)


if __name__ == "__main__":
    main()
