"""
Web CLI Commands - Start and manage the web server

Provides commands for:
- serve: Start the web server
- web: Open the web interface in browser
"""

import sys
from pathlib import Path
from typing import Optional

import click
from rich.console import Console

console = Console()


@click.command()
@click.option("--host", "-h", default="127.0.0.1", help="Host to bind to")
@click.option("--port", "-p", default=8080, help="Port to listen on")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--debug", is_flag=True, help="Enable debug mode")
@click.option("--reload", is_flag=True, help="Enable auto-reload")
@click.option("--open", "open_browser", is_flag=True, help="Open browser automatically")
def serve(
    host: str,
    port: int,
    path: Optional[str],
    debug: bool,
    reload: bool,
    open_browser: bool,
):
    """
    Start the groknroll web server

    Examples:

        # Start server on default port
        groknroll serve

        # Start on custom port
        groknroll serve --port 3000

        # Start with debug mode
        groknroll serve --debug --reload

        # Open browser automatically
        groknroll serve --open
    """
    project_path = Path(path) if path else Path.cwd()

    console.print("[bold cyan]Starting groknroll web server...[/bold cyan]")
    console.print(f"  [dim]Host:[/dim] {host}")
    console.print(f"  [dim]Port:[/dim] {port}")
    console.print(f"  [dim]Project:[/dim] {project_path}")
    console.print()

    url = f"http://{host}:{port}"
    console.print(f"[bold green]Server starting at:[/bold green] {url}")
    console.print(f"[dim]API docs at:[/dim] {url}/api/docs")
    console.print()

    # Open browser if requested
    if open_browser:
        import webbrowser

        webbrowser.open(url)

    try:
        from groknroll.web import run_server

        run_server(
            host=host,
            port=port,
            project_path=project_path,
            debug=debug,
            reload=reload,
        )
    except ImportError:
        console.print("[bold red]Error:[/bold red] Web dependencies not installed")
        console.print("\n[yellow]Install with:[/yellow] pip install fastapi uvicorn")
        sys.exit(1)
    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@click.command()
@click.option("--port", "-p", default=8080, help="Port for the server")
@click.option("--path", type=click.Path(exists=True), help="Project path")
def web(port: int, path: Optional[str]):
    """
    Open the web interface in your browser

    This starts the server and opens the browser automatically.

    Example:
        groknroll web
        groknroll web --port 3000
    """
    import threading
    import time
    import webbrowser

    project_path = Path(path) if path else Path.cwd()

    url = f"http://127.0.0.1:{port}"

    console.print("[bold cyan]Opening groknroll web interface...[/bold cyan]")
    console.print(f"[dim]URL:[/dim] {url}")
    console.print()

    # Open browser after a short delay
    def open_browser_delayed():
        time.sleep(1.5)
        webbrowser.open(url)

    threading.Thread(target=open_browser_delayed, daemon=True).start()

    try:
        from groknroll.web import run_server

        run_server(
            host="127.0.0.1",
            port=port,
            project_path=project_path,
            debug=False,
            reload=False,
        )
    except ImportError:
        console.print("[bold red]Error:[/bold red] Web dependencies not installed")
        console.print("\n[yellow]Install with:[/yellow] pip install fastapi uvicorn")
        sys.exit(1)
    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)
