import argparse
import re
from pathlib import Path

def patch_django_files(base_dir):
    
    settings_files = list(base_dir.glob('*/settings.py'))
    
    if not settings_files:
        print("⚠️  Aviso: Não encontrei o arquivo 'settings.py'. Você rodou o comando na raiz de um projeto Django recém-criado?")
        return False
        
    settings_path = settings_files[0]
    urls_path = settings_path.parent / 'urls.py'

    settings_content = settings_path.read_text(encoding='utf-8')
    
    if "'django_cotton'" not in settings_content:
        settings_content = re.sub(
            r'INSTALLED_APPS = \[',
            "INSTALLED_APPS = [\n    'django_cotton',\n    'models',",
            settings_content
        )
        
    if "BASE_DIR / 'app'" not in settings_content:
        settings_content = re.sub(
            r"'DIRS': \[\]",
            "'DIRS': [BASE_DIR / 'app', BASE_DIR]",
            settings_content
        )
    
    if "COTTON_DIR" not in settings_content:
        cotton_config = "\nCOTTON_DIR = 'components'\n"
        root_urlconf_pattern = r'(ROOT_URLCONF = .*?\n)'
        match = re.search(root_urlconf_pattern, settings_content)
        if match:
            insert_position = match.end()
            settings_content = (
                settings_content[:insert_position] + 
                cotton_config + 
                settings_content[insert_position:]
            )
        
    settings_path.write_text(settings_content, encoding='utf-8')
    print(f"⚙️  {settings_path.name} atualizado: Cotton, Models, Templates e COTTON_DIR configurados!")

    if urls_path.exists():
        urls_content = urls_path.read_text(encoding='utf-8')
        
        if "generate_urlpatterns" not in urls_content:
            imports = "from next_django.router import generate_urlpatterns\nfrom django.conf import settings\n"
            
            urls_content = imports + urls_content + "\n# Roteamento Mágico do Next-Django\nurlpatterns += generate_urlpatterns(settings.BASE_DIR)\n"
            
            urls_path.write_text(urls_content, encoding='utf-8')
            print(f"🔗 {urls_path.name} atualizado: Auto-Router do Next-Django ativado!")

    return True

def create_boilerplate():
    base_dir = Path.cwd()
    print("🚀 Inicializando o Next-Django...")

    if not patch_django_files(base_dir):
        print("❌ Operação abortada. Crie um projeto Django primeiro com: django-admin startproject nome .")
        return

    pastas = ["app", "components/ui", "models", "api"]
    for pasta in pastas:
        (base_dir / pasta).mkdir(parents=True, exist_ok=True)

    layout_content = """<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Next-Django App</title>
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen font-sans antialiased">
    <main class="max-w-4xl mx-auto p-8">
        {% block content %}
        {% endblock %}
    </main>
</body>
</html>"""
    (base_dir / "app/layout.html").write_text(layout_content, encoding='utf-8')

    page_py = "from django.shortcuts import render\n\ndef page(request):\n    return render(request, 'page.html')\n"
    (base_dir / "app/page.py").write_text(page_py, encoding='utf-8')

    page_html = """{% extends "layout.html" %}
    
    {% block content %}
    <div class="flex flex-col items-center justify-center space-y-6 mt-20 text-center">
        <h1 class="text-5xl font-extrabold tracking-tight text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-blue-500">
            Bem-vindo ao Next-Django 🚀
        </h1>
        <p class="text-xl text-slate-400 max-w-2xl">A mágica da configuração automática funcionou perfeitamente!</p>
        <div class="pt-8"><c-ui.button>Comece a codar!</c-ui.button></div>
    </div>
    {% endblock %}
    """
    (base_dir / "app/page.html").write_text(page_html, encoding='utf-8')

    button_html = """<button class="bg-blue-600 hover:bg-blue-500 text-white font-semibold py-2 px-6 rounded-lg shadow-md transition-all duration-200">
    {{ slot }}
</button>"""
    (base_dir / "components/ui/button.html").write_text(button_html, encoding='utf-8')

    (base_dir / "models/__init__.py").write_text("# Registre seus modelos aqui\n", encoding='utf-8')
    apps_py = "from django.apps import AppConfig\n\nclass ModelsConfig(AppConfig):\n    default_auto_field = 'django.db.models.BigAutoField'\n    name = 'models'\n"
    (base_dir / "models/apps.py").write_text(apps_py, encoding='utf-8')

    api_py = "from ninja import Router\n\nrouter = Router()\n\n@router.get('/')\ndef hello(request):\n    return {'mensagem': 'API Next-Django rodando com sucesso!'}\n"
    (base_dir / "api/hello.py").write_text(api_py, encoding='utf-8')

    print("✅ Pastas 'app', 'api', 'components' e 'models' geradas com sucesso!")
    print("🎉 Seu projeto está pronto! Para testar, rode: python manage.py runserver")

def main():
    parser = argparse.ArgumentParser(description="CLI do Next-Django")
    parser.add_argument("command", choices=["init"], help="Inicializa a estrutura do projeto")
    args = parser.parse_args()
    
    if args.command == "init":
        create_boilerplate()

if __name__ == "__main__":
    main()