import os
from app.services.markdown_render import render_markdown_with_jinja

def process_markdown_files(input_dir: str, output_dir: str):
    """
    Recursively process all Markdown files in the input directory,
    render them to HTML, and save them to the output directory.
    """
    for root, _, files in os.walk(input_dir):
        for file in files:
            if file.endswith(".md"):
                input_file_path = os.path.join(root, file)

                # Determine output file path (convert .md to .html)
                relative_path = os.path.relpath(input_file_path, input_dir)
                output_file_path = os.path.join(output_dir, os.path.splitext(relative_path)[0] + ".html")

                # Ensure the output directory exists
                os.makedirs(os.path.dirname(output_file_path), exist_ok=True)

                # Read Markdown content
                with open(input_file_path, "r", encoding="utf-8") as md_file:
                    markdown_content = md_file.read()

                # Render Markdown with Jinja2
                print(f"Processing: {input_file_path} -> {output_file_path}")
                rendered_html = render_markdown_with_jinja(markdown_content)

                # Write the rendered HTML to the output file
                with open(output_file_path, "w", encoding="utf-8") as html_file:
                    html_file.write(rendered_html)

    print("Markdown processing complete!")

if __name__ == "__main__":
    # Input directory containing Markdown files
    input_directory = "./data"

    # Output directory where HTML files will be stored
    output_directory = "./data"

    # Start the processing
    process_markdown_files(input_directory, output_directory)
