from __future__ import annotations

from fnmatch import fnmatch
from pprint import pprint
from typing import Type

from auto_everything.disk import Disk
disk = Disk()

from auto_everything.io import IO
io_ = IO()

from dateutil import parser

def parse_time_string_and_do_a_format(time_string):
    date_time = parser.parse(time_string)
    return date_time.strftime("%Y-%m-%d")

gitignore_file_path = ".gitignore"
gitignore_text = ""
if disk.exists(gitignore_file_path):
    gitignore_text = io_.read(gitignore_file_path)
    gitignore_text += "\n./.git/"
#print(gitignore_text)

text = """
# Table of contents
""".strip()

text += "\n\n"

root = disk.get_folder_and_files_tree(".", type_limiter=[".md"], gitignore_text=gitignore_text)

def travel(node):
    global text
    if node.children == None:
        if node.level not in [0, 1, 2]:
            if node.level == 3:
                # day note
                prefix = "./"
                date_string = node.folder.removeprefix(prefix) + "/" + node.name.removesuffix(".md")
                date_string = parse_time_string_and_do_a_format(date_string)
                text += "* " * (node.level-1) + f"[{date_string}]({node.path})" + "\n"
            else:
                # other notes
                text += "* " * (node.level-1) + f"[{node.name.removesuffix('.md')}]({node.path})" + "\n"
                pass
        return
    
    if node.level not in [0]:
        if node.level == 1:
            # year
            text += "* " * (node.level-1) + f"[{node.name}]({node.path})" + "\n"
        if node.level == 2:
            # month
            text += "* " * (node.level-1) + f"[{node.name}]({node.path})" + "\n"
        if node.level == 3:
            # day
            prefix = "./"
            date_string = node.folder.removeprefix(prefix) + "/" + node.name.removesuffix(".md")
            date_string = parse_time_string_and_do_a_format(date_string)
            text += "* " * (node.level-1) + f"{date_string}" + "\n"

    for child in node.children:
        travel(child)

travel(root)

#io_.write("./SUMMARY.md", text)
io_.write("./README.md", text)