from fastapi.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
import os

env = Environment(loader=FileSystemLoader("."), auto_reload=True)

def find_layouts(path):
    """Find all layout files in parent directories"""
    layouts = []
    current_path = path
    while current_path:
        layout_path = os.path.join(current_path, "layout.html")
        if os.path.exists(layout_path):
            layouts.insert(0, layout_path)
        current_path = os.path.dirname(current_path)
    return layouts

def useView(data, path):
    try:
        template_path = f"app{path}/view.html"
        
        # Find all layout templates in parent directories
        layouts = find_layouts(path)
        
        # If no layouts found, use default root layout
        if not layouts:
            root_layout = None
            try:
                root_layout = env.get_template("app/layout.html")
            except TemplateNotFound:
                # Create default root layout if not found
                layout_content = """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="utf-8">
                    <title>{% block title %}{% endblock %}</title>
                </head>
                <body>
                    {% block children %}{% endblock %}
                </body>
                </html>
                """
                root_layout = env.from_string(layout_content)
            layouts = [root_layout] if root_layout else []
        
        # Get the page template
        page = env.get_template(template_path)
        
        # Render page content within nested layouts
        content = page.render(data)
        for layout in layouts:
            layout_template = env.get_template(layout)
            content = layout_template.render(children=content, **data)
            
        return HTMLResponse(content=content)
    
    except TemplateNotFound as e:
        return HTMLResponse(content=f"Template not found: {str(e)}", status_code=404)
    except Exception as e:
        return HTMLResponse(content=f"Error rendering template: {str(e)}", status_code=500)
