import os
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command

class Command(BaseCommand):
    help = "Creates a Django app with custom structure (urls.py, views/ and models/ directories)"

    def add_arguments(self, parser):
        parser.add_argument("app_name", type=str, help="Name of the application to create")

    def handle(self, *args, **options):
        app_name = options["app_name"]
        
        # Call Django's startapp command to create basic structure
        call_command("startapp", app_name)
        
        # Define paths
        app_dir = os.path.join(os.getcwd(), app_name)
        views_dir = os.path.join(app_dir, "views")
        models_dir = os.path.join(app_dir, "models")
        urls_file = os.path.join(app_dir, "urls.py")
        views_file = os.path.join(app_dir, "views.py")
        models_file = os.path.join(app_dir, "models.py")
        
        try:
            # Create views/ directory and __init__.py
            os.makedirs(views_dir, exist_ok=True)
            with open(os.path.join(views_dir, "__init__.py"), "w") as f:
                f.write("")
            
            # Create models/ directory and __init__.py
            os.makedirs(models_dir, exist_ok=True)
            with open(os.path.join(models_dir, "__init__.py"), "w") as f:
                f.write("")
            
            # Create urls.py
            with open(urls_file, "w") as f:
                f.write("""from django.urls import path

urlpatterns = [
    # Define your URL patterns here
]
""")
            
            # Remove original views.py and models.py
            if os.path.exists(views_file):
                os.remove(views_file)
            if os.path.exists(models_file):
                os.remove(models_file)
            
            self.stdout.write(self.style.SUCCESS(f"Successfully created app '{app_name}' with custom structure"))
            
        except Exception as e:
            raise CommandError(f"Error creating app structure: {str(e)}")

