# next_django/cli.py
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'.")
        return False
        
    settings_path = settings_files[0]
    urls_path = settings_path.parent / 'urls.py'

    # Modificando o SETTINGS.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 "'next_django.context_processors.htmx'" not in settings_content:
        settings_content = re.sub(
            r"'django\.template\.context_processors\.request',",
            "'django.template.context_processors.request',\n                'next_django.context_processors.htmx',",
            settings_content
        )
        
    settings_path.write_text(settings_content, encoding='utf-8')
    print(f"⚙️  {settings_path.name} atualizado: HTMX, Cotton e Rotas configurados!")

    # Modificando o URLS.PY
    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 ativado!")

    return True

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

    if not patch_django_files(base_dir):
        return

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

    # NOVO LAYOUT COM HTMX E LOADING BAR
    layout_content = """{% if not is_htmx %}
<!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.tailwindcss.com"></script>
    <script src="https://unpkg.com/htmx.org@1.9.10"></script>
    <style>
        .htmx-indicator { opacity: 0; transition: opacity 200ms ease-in; height: 3px; background: #3b82f6; position: fixed; top: 0; left: 0; width: 100%; z-index: 50; }
        .htmx-request .htmx-indicator { opacity: 1; }
        .htmx-request.htmx-indicator { opacity: 1; }
    </style>
</head>
<body class="bg-slate-900 text-slate-100 min-h-screen font-sans antialiased" hx-ext="preload">
    <div id="loading-bar" class="htmx-indicator"></div>
    <main id="next-root" class="max-w-4xl mx-auto p-8">
{% endif %}

        {% block content %}
        {% endblock %}

{% if not is_htmx %}
    </main>
</body>
</html>
{% endif %}"""
    (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, 'sobre/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">
            Next-Django v0.5 🚀
        </h1>
        <p class="text-xl text-slate-400 max-w-2xl">A navegação instantânea SPA está ativada!</p>
        
        <div class="pt-8 flex space-x-4">
            <c-ui.link href="/sobre">
                <c-ui.button>Página Sobre</c-ui.button>
            </c-ui.link>
        </div>
    </div>
{% endblock %}"""
    (base_dir / "app/page.html").write_text(page_html, encoding='utf-8')

    (base_dir / "app/sobre").mkdir(parents=True, exist_ok=True)
    sobre_html = """{% extends "layout.html" %}
    {% block content %}
    <div class="mt-20 text-center">
        <h1 class="text-4xl font-bold mb-4">Sobre Nós</h1>
        <p class="mb-8">Você navegou até aqui sem a tela piscar!</p>
        <c-ui.link href="/">Voltar para Home</c-ui.link>
    </div>
{% endblock %}"""
    (base_dir / "app/sobre/page.html").write_text(sobre_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')

    link_html = """<a 
    href="{{ href }}" 
    hx-get="{{ href }}" 
    hx-push-url="true" 
    hx-target="#next-root" 
    hx-swap="innerHTML"
    hx-indicator="#loading-bar"
    class="cursor-pointer {{ class|default:'text-blue-500 hover:text-blue-400 underline transition-colors' }}"
>
    {{ slot }}
</a>"""
    (base_dir / "components/ui/link.html").write_text(link_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, Arquivos Mágicos e Componentes gerados com sucesso!")

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()