import os
from markdown import markdown
from docx import Document

def convert_md_to_docx(md_file_path, docx_file_path):
    """Converts a Markdown file to a Word document."""
    with open(md_file_path, 'r', encoding='utf-8') as md_file:
        md_content = md_file.read()

    # Convert Markdown to HTML
    html_content = markdown(md_content)

    # Create a Word document and add the HTML content
    doc = Document()
    doc.add_paragraph(html_content)
    doc.save(docx_file_path)
    print(f"Converted: {md_file_path} -> {docx_file_path}")

def convert_all_md_to_docx(root_directory, output_directory):
    """Traverse the directory tree and convert all .md files to .docx, storing them in a mirrored structure."""
    for dirpath, dirnames, filenames in os.walk(root_directory):
        for filename in filenames:
            if filename.endswith('.md'):
                md_file_path = os.path.join(dirpath, filename)

                # Create mirrored directory structure in the output directory
                relative_path = os.path.relpath(dirpath, root_directory)
                target_dir = os.path.join(output_directory, relative_path)
                os.makedirs(target_dir, exist_ok=True)

                # Define the output .docx file path
                docx_file_path = os.path.join(target_dir, os.path.splitext(filename)[0] + '.docx')

                try:
                    convert_md_to_docx(md_file_path, docx_file_path)
                except Exception as e:
                    print(f"Failed to convert {md_file_path}: {e}")

if __name__ == "__main__":
    # Prompt user for the root directory and output directory
    root_dir = input("Enter the root directory to scan for Markdown files: ").strip()
    output_dir = input("Enter the output directory to store converted files: ").strip()

    if os.path.exists(root_dir):
        os.makedirs(output_dir, exist_ok=True)  # Ensure output directory exists
        convert_all_md_to_docx(root_dir, output_dir)
    else:
        print("The specified root directory does not exist.")