import click
import os
import subprocess
from pathlib import Path
from rich.console import Console

console = Console()


@click.group()
def cli():
    """FeatherOS CLI - Build full-stack apps with minimal code"""
    pass


@cli.command()
@click.argument('project_name', default='my-app')
def init(project_name):
    """Initialize a new FeatherOS project"""
    console.print(f"[cyan]Creating new FeatherOS project: {project_name}[/cyan]")
    
    project_path = Path(project_name)
    project_path.mkdir(exist_ok=True)
    
    app_content = '''import feather as ft

app = ft.App(title="My FeatherOS App")

@app.page("/")
def home():
    ft.title("Welcome to FeatherOS")
    
    with ft.form() as form:
        name = ft.input("Name", placeholder="Enter your name", required=True)
        email = ft.input("Email", type="email", placeholder="your@email.com")
        submit = ft.button("Submit")
    
    if form.submitted:
        ft.db.save("users", {
            "name": name.value,
            "email": email.value
        })
        ft.success(f"Welcome {name.value}!")
        ft.rerun()
    
    users = ft.db.query("users", order_by="created_at DESC", limit=10)
    
    if users:
        ft.title("Recent Users", level=2)
        ft.table(users, headers=["id", "name", "email", "created_at"])

if __name__ == "__main__":
    app.run()
'''
    
    app_file = project_path / 'app.py'
    with open(app_file, 'w') as f:
        f.write(app_content)
    
    console.print(f"[green]✓ Project created successfully![/green]")
    console.print(f"\n[yellow]Next steps:[/yellow]")
    console.print(f"  cd {project_name}")
    console.print(f"  feather serve")


@cli.command()
@click.option('--host', default='0.0.0.0', help='Host to bind to')
@click.option('--port', default=5000, help='Port to bind to')
def serve(host, port):
    """Run the FeatherOS development server"""
    console.print(f"[cyan]Starting FeatherOS server on {host}:{port}[/cyan]")
    
    if not os.path.exists('app.py'):
        console.print("[red]Error: app.py not found in current directory[/red]")
        console.print("[yellow]Run 'feather init' to create a new project[/yellow]")
        return
    
    os.environ['FLASK_ENV'] = 'development'
    
    try:
        subprocess.run(['python', 'app.py'], check=True)
    except KeyboardInterrupt:
        console.print("\n[yellow]Server stopped[/yellow]")
    except subprocess.CalledProcessError:
        console.print("[red]Error running app.py[/red]")


@cli.command()
@click.argument('plugin_name')
def plugin(plugin_name):
    """Install a plugin from the FeatherOS server"""
    from .plugins.installer import PluginInstaller
    
    installer = PluginInstaller()
    installer.install(plugin_name)


if __name__ == '__main__':
    cli()
