"""
NeuroFlow CLI - Command-line interface for launching NeuroFlow

Usage:
    neuroflow              # Start the server on default port 8000
    neuroflow --port 3000  # Start on a custom port
    neuroflow --help       # Show help
"""

import argparse
import os
import sys
import webbrowser
from pathlib import Path
from threading import Timer


def get_static_dir() -> Path:
    """Get the path to the static files directory."""
    # Check multiple locations for static files
    locations = [
        # Development: static folder in package directory
        Path(__file__).parent.parent / "static",
        # Installed: in share directory
        Path(sys.prefix) / "share" / "neuroflow" / "static",
        # User install
        Path.home() / ".local" / "share" / "neuroflow" / "static",
    ]
    
    for loc in locations:
        if loc.exists() and (loc / "index.html").exists():
            return loc
    
    return locations[0]  # Return first location even if doesn't exist


def get_data_dir() -> Path:
    """Get the path to the data files directory."""
    locations = [
        Path(__file__).parent.parent / "data",
        Path(sys.prefix) / "share" / "neuroflow" / "data",
        Path.home() / ".local" / "share" / "neuroflow" / "data",
    ]
    
    for loc in locations:
        if loc.exists():
            return loc
    
    # Create default data directory
    default_dir = Path.cwd() / "data"
    default_dir.mkdir(exist_ok=True)
    return default_dir


def open_browser(port: int):
    """Open the browser after a short delay."""
    webbrowser.open(f"http://localhost:{port}")


def main():
    parser = argparse.ArgumentParser(
        description="NeuroFlow - A local-first, node-based ML orchestrator",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  neuroflow                    Start NeuroFlow on http://localhost:8000
  neuroflow --port 3000        Start on port 3000
  neuroflow --no-browser       Don't open browser automatically
  neuroflow --host 0.0.0.0     Allow external connections

For more information, visit: https://github.com/aayushgokhale/neuroflow
        """
    )
    
    parser.add_argument(
        "--port", "-p",
        type=int,
        default=8000,
        help="Port to run the server on (default: 8000)"
    )
    
    parser.add_argument(
        "--host", "-H",
        type=str,
        default="127.0.0.1",
        help="Host to bind the server to (default: 127.0.0.1)"
    )
    
    parser.add_argument(
        "--no-browser",
        action="store_true",
        help="Don't open browser automatically"
    )
    
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development"
    )
    
    parser.add_argument(
        "--version", "-v",
        action="version",
        version="NeuroFlow 0.1.0"
    )
    
    args = parser.parse_args()
    
    # Set environment variables for the app
    os.environ["NEUROFLOW_STATIC_DIR"] = str(get_static_dir())
    os.environ["NEUROFLOW_DATA_DIR"] = str(get_data_dir())
    
    # Print startup message
    print(r"""
    _   _                      _____ _               
   | \ | |                    |  ___| |              
   |  \| | ___ _   _ _ __ ___ | |_  | | _____      __
   | . ` |/ _ \ | | | '__/ _ \|  _| | |/ _ \ \ /\ / /
   | |\  |  __/ |_| | | | (_) | |   | | (_) \ V  V / 
   \_| \_/\___|\__,_|_|  \___/\_|   |_|\___/ \_/\_/  
                                                     
    """)
    print(f"  🚀 Starting NeuroFlow server...")
    print(f"  📍 URL: http://{args.host}:{args.port}")
    print(f"  📁 Data directory: {get_data_dir()}")
    print(f"  📦 Static files: {get_static_dir()}")
    print()
    print("  Press Ctrl+C to stop the server")
    print()
    
    # Open browser after a short delay (if not disabled)
    if not args.no_browser:
        Timer(1.5, open_browser, args=[args.port]).start()
    
    # Start the server
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host=args.host,
        port=args.port,
        reload=args.reload,
        log_level="info"
    )


if __name__ == "__main__":
    main()
