import re
from pathlib import Path
import importlib.util
from django.urls import path
from ninja import NinjaAPI

def generate_urlpatterns(base_dir):
    base_path = Path(base_dir)
    urlpatterns = []

    app_dir = base_path / 'app'
    if app_dir.exists():
        for py_file in app_dir.rglob('page.py'):
            rel_path = py_file.relative_to(app_dir)
            dir_parts = list(rel_path.parent.parts)
            clean_parts = [p for p in dir_parts if not (p.startswith('(') and p.endswith(')'))]
            
            route_parts = [re.sub(r'\[(.*?)\]', r'<\1>', part) for part in clean_parts]
            route_string = '/'.join(route_parts)
            if route_string: route_string += '/'

            module_name = f"app_views.{'_'.join(rel_path.parent.parts)}"
            spec = importlib.util.spec_from_file_location(module_name, py_file)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)

            if hasattr(module, 'page'):
                urlpatterns.append(path(route_string, getattr(module, 'page')))
                print(f"✅ Rota UI: /{route_string} -> {py_file}")

    api_dir = base_path / 'api'
    
    api = NinjaAPI(title="Next-Django API", version="1.0.0")
    api_has_routes = False

    if api_dir.exists():
        for py_file in api_dir.rglob('*.py'):
            if py_file.name == '__init__.py':
                continue
            
            rel_path = py_file.relative_to(api_dir)
            route_parts = list(rel_path.with_suffix('').parts)
            
            route_string = '/' + '/'.join(route_parts)

            module_name = f"api_views.{'_'.join(route_parts)}"
            spec = importlib.util.spec_from_file_location(module_name, py_file)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)

            if hasattr(module, 'router'):
                api.add_router(route_string, module.router)
                api_has_routes = True
                print(f"🥷 Rota Ninja: /api{route_string} -> {py_file}")

    if api_has_routes:
        urlpatterns.append(path('api/', api.urls))

    return urlpatterns