from textnode import TextNode,TextType
from htmlnode import LeafNode,ParentNode
from conversions import markdown_to_html_node
import shutil
import os
import re

def extract_title(markdown):
    split = markdown.split("\n")
    for item in split:
        if item.startswith("# "):
            return(item.strip("# "))
    raise Exception("no title found")

def empty_public():
   dir_path = os.path.abspath("./public/")
   if os.path.exists(dir_path):
      shutil.rmtree(dir_path, ignore_errors=True)
   os.mkdir(dir_path,mode=0o755)

def copy_directory_recursive(src, dest):
    # Ensure source directory exists
    if not os.path.exists(src):
        raise FileNotFoundError(f"Source directory '{src}' not found.")
    
    # Remove destination directory if it exists
    if os.path.exists(dest):
        shutil.rmtree(dest)
    
    # Recursively copy source directory to destination
    shutil.copytree(src, dest)

def get_files_from_path_recursively(path):
    files = []
    for entry in os.scandir(path):
        if entry.is_file():
            files.append(entry.path)  # Use full path
        elif entry.is_dir():
            # Recursively get files from subdirectory
            files.extend(get_files_from_path_recursively(entry.path))
    return files

def generate_page(from_path, template_path, dest_path):
    for file_path in get_files_from_path_recursively(from_path):
        match = re.search(r"content/(.*)", file_path)
        if match:
            relative_path = match.group(1)
            
            print(f"Generating page from {file_path} to {dest_path}{re.sub(r'\.md$', '.html', relative_path)} using {template_path}")
            
            # Read the markdown file
            with open(file_path, 'r') as file:
                md = file.read()

            # Read the template
            with open(template_path, 'r') as file:
                template = file.read()
            
            title = extract_title(md)
            html = markdown_to_html_node(md).to_html()
            
            final_html = template.replace("{{ Title }}", title)
            final_html = final_html.replace("{{ Content }}", html)
            
            # Create output directory if it doesn't exist
            output_dir = os.path.dirname(f"{dest_path}/{relative_path}")
            os.makedirs(output_dir, exist_ok=True)
            
            # Write the final HTML
            with open(f"{dest_path}/{re.sub(r'\.md$', '.html', relative_path)}", "w") as f:
                f.write(final_html)

def main():
    empty_public()
    copy_directory_recursive("./static/","./public/")
    generate_page("./content/","./template.html","./public/")

if __name__=="__main__":
    main()
