import os
import sys

def start_app():
    if len(sys.argv) < 3:
        print("Usage: valerius_flow startapp <app_name>")
        return

    app_name = sys.argv[2]
    class_name = app_name.capitalize()

    # ASGI Templates: Handlers are now 'async' and return dicts for auto-JSON
    handlers_content = f"""class {class_name}Resource:
    async def get(self, req):
        return {{"message": "Welcome to the {app_name} app!"}}
"""

    routes_content = f"""from .handlers import {class_name}Resource

routes = [
    ("/{app_name}", {class_name}Resource),
]
"""

    # Create directory and files
    os.makedirs(app_name, exist_ok=True)
    
    with open(os.path.join(app_name, "__init__.py"), "w") as f:
        f.write("")

    with open(os.path.join(app_name, "handlers.py"), "w") as f:
        f.write(handlers_content)

    with open(os.path.join(app_name, "routes.py"), "w") as f:
        f.write(routes_content)

    # Path to nested settings
    settings_path = "config/settings/base.py"
    
    if os.path.exists(settings_path):
        with open(settings_path, "r") as f:
            lines = f.readlines()

        with open(settings_path, "w") as f:
            for line in lines:
                f.write(line)
                if "INSTALLED_APPS = [" in line:
                    f.write(f"    '{app_name}.routes',\n")
        
        print(f"✓ App '{app_name}' created successfully!")
        print(f"✓ Registered '{app_name}.routes' in settings.py")
    else:
        print(f"✓ App '{app_name}' created successfully!")
        print(f"⚠ Warning: Could not find config/settings/base.py")
        print(f"  Next: Add '{app_name}.routes' to INSTALLED_APPS manually.")


def start_project():
    if len(sys.argv) < 3:
        print("Usage: valerius_flow startproject <project_name>")
        return

    project_name = sys.argv[2]

    app_content = """from valerius_flow.framework import App

# Initializing as an ASGI application
app = App(settings_module='config.settings.base')
"""
    
    settings_content = """INSTALLED_APPS = []

MIDDLEWARE = [
    'valerius_flow.middlewares.logger.LoggerMiddleware',
    'valerius_flow.middlewares.json.JsonErrorMiddleware',
]
"""

    manage_content = """import sys
import os
from valerius_flow.management import create_app

def main():
    if len(sys.argv) < 2:
        print("Usage: python manage.py [run|startapp]")
        return

    command = sys.argv[1]
    
    if command == "run":
        print("ValeriusFlow dev server starting...")
        os.system("uvicorn app:app --reload")
        
    elif command == "startapp":
        if len(sys.argv) > 2:
            create_app(sys.argv[2])
        else:
            print("Error: Please provide an app name.")
            
    else:
        print(f"Unknown command: {command}")

if __name__ == "__main__":
    main()
"""

    files = {
        "app.py": app_content,
        "config/__init__.py": "",
        "config/settings/__init__.py": "",
        "config/settings/base.py": settings_content,
        "manage.py": manage_content,
        "requirements/base.txt": "valerius_flow\nuvicorn\nstarlette\nparse",
        "env/.env": "DEBUG=True"
    }

    os.makedirs(project_name, exist_ok=True)

    for relative_path, content in files.items():
        full_path = os.path.join(project_name, relative_path)
        directory = os.path.dirname(full_path)
        
        if directory:
            os.makedirs(directory, exist_ok=True)
            
        with open(full_path, "w") as f:
            f.write(content)
    
    print(f"✓ Project '{project_name}' created successfully!")
    print(f"\\nNext steps:")
    print(f"  cd {project_name}")
    print(f"  pip install -r requirements/base.txt")
    print(f"  python manage.py run")


def print_help():
    help_text = """
ValeriusFlow - A Django-inspired Async API framework

Usage:
  valerius_flow startproject <project_name>  Create a new project
  valerius_flow startapp <app_name>          Create a new app (run inside project)
  valerius_flow --help                       Show this help message
  valerius_flow --version                    Show version information
"""
    print(help_text)

def print_version():
    print("ValeriusFlow 0.1.1 (ASGI)")

def main():
    if len(sys.argv) < 2:
        print_help()
        return
    
    command = sys.argv[1]
    
    if command in ('--help', '-h', 'help'):
        print_help()
    elif command in ('--version', '-v', 'version'):
        print_version()
    elif command == 'startproject':
        start_project()
    elif command == 'startapp':
        start_app()
    else:
        print(f"Error: Unknown command '{command}'")
        sys.exit(1)

if __name__ == '__main__':
    main()
