"""
OMNIWEB CLI - Command-line interface
Author: Juste Elysée MALANDILA
"""

import sys
import os
from pathlib import Path


def create_project(name: str):
    """Create a new OMNIWEB project."""
    project_dir = Path(name)
    
    if project_dir.exists():
        print(f"❌ Error: Directory '{name}' already exists!")
        return
    
    print(f"🌟 Creating OMNIWEB project: {name}")
    
    # Create structure
    project_dir.mkdir()
    (project_dir / "app").mkdir()
    (project_dir / "static").mkdir()
    (project_dir / "templates").mkdir()
    
    # Create main.py
    main_content = '''"""
{name} - OMNIWEB Application
"""

from omniweb import OmniWeb, Model

app = OmniWeb(
    title="{name}",
    version="0.1.0",
    description="A OMNIWEB web application",
    debug=True,
)


# Models
class User(Model):
    __table__ = "users"


# Routes
@app.get("/")
async def home():
    """Home page."""
    return {{
        "message": "Welcome to {name}!",
        "framework": "OMNIWEB",
        "docs": "https://omniweb.readthedocs.io"
    }}


@app.get("/users")
async def list_users():
    """List all users."""
    users = await User.all()
    return {{"users": [u.dict() for u in users]}}


@app.get("/users/{{id}}")
async def get_user(id: int):
    """Get user by ID."""
    user = await User.get(id=id)
    if not user:
        return {{"error": "User not found"}}, 404
    return user.dict()


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, reload=True)
'''.format(name=name)
    
    (project_dir / "main.py").write_text(main_content)
    
    # Create requirements.txt
    requirements = """omniweb>=0.1.0
uvicorn[standard]>=0.25.0
"""
    (project_dir / "requirements.txt").write_text(requirements)
    
    # Create .gitignore
    gitignore = """__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
.venv/
*.db
*.sqlite3
.env
.DS_Store
"""
    (project_dir / ".gitignore").write_text(gitignore)
    
    # Create README.md
    readme = f"""# {name}

A OMNIWEB web application.

## Installation

```bash
pip install -r requirements.txt
```

## Run

```bash
python main.py
```

Or:

```bash
omniweb run
```

## Documentation

- [OMNIWEB Docs](https://omniweb.readthedocs.io)
- [GitHub](https://github.com/jdevsky/omniweb)

---

Created with ❤️ using **OMNIWEB** - The Next-Gen Python Web Framework
"""
    (project_dir / "README.md").write_text(readme)
    
    print(f"""
✅ Project created successfully!

📁 Structure:
   {name}/
   ├── app/              # Application modules
   ├── static/           # Static files (CSS, JS, images)
   ├── templates/        # HTML templates
   ├── main.py           # Main application file
   ├── requirements.txt  # Python dependencies
   └── README.md         # Project documentation

🚀 Next steps:
   1. cd {name}
   2. pip install -r requirements.txt
   3. python main.py

📚 Visit: http://127.0.0.1:8000
    """)


def run_server():
    """Run the OMNIWEB development server."""
    # Look for main.py in current directory
    if not Path("main.py").exists():
        print("❌ Error: main.py not found in current directory!")
        print("💡 Create a project with: omniweb new <project_name>")
        return
    
    print("🚀 Starting OMNIWEB development server...")
    os.system("python main.py")


def show_version():
    """Show OMNIWEB version."""
    from . import __version__
    print(f"OMNIWEB v{__version__}")
    print("The Next-Gen Python Web Framework")
    print("\nCreated by: Juste Elysée MALANDILA")
    print("LinkedIn: https://linkedin.com/in/justelm/")


def show_help():
    """Show help message."""
    print("""
╔══════════════════════════════════════════════════════════╗
║  🌟 OMNIWEB CLI - Command Line Interface                 ║
╚══════════════════════════════════════════════════════════╝

Usage:
    omniweb <command> [options]

Commands:
    new <name>      Create a new OMNIWEB project
    run             Run the development server
    version         Show OMNIWEB version
    help            Show this help message

Examples:
    omniweb new myapp        # Create new project
    omniweb run              # Start dev server
    omniweb version          # Show version

Documentation:
    https://omniweb.readthedocs.io

GitHub:
    https://github.com/jdevsky/omniweb
    """)


def main():
    """Main CLI entry point."""
    args = sys.argv[1:]
    
    if not args or args[0] in ["help", "--help", "-h"]:
        show_help()
        return
    
    command = args[0]
    
    if command == "new":
        if len(args) < 2:
            print("❌ Error: Project name required!")
            print("Usage: omniweb new <project_name>")
            return
        create_project(args[1])
    
    elif command == "run":
        run_server()
    
    elif command in ["version", "--version", "-v"]:
        show_version()
    
    else:
        print(f"❌ Unknown command: {command}")
        print("Run 'omniweb help' for usage information")


if __name__ == "__main__":
    main()
