"""Visual Workflow Server - Entry point

Runs both:
- HTTP server for frontend (port 8766)
- WebSocket server for real-time communication (port 8765)

Usage:
    python -m cubesquare.visual
    python -m cubesquare.visual --port 8765 --http-port 8766
"""

import asyncio
import argparse
import webbrowser
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading

try:
    import websockets
    ws_serve = websockets.serve
    HAS_WEBSOCKETS = True
except ImportError:
    HAS_WEBSOCKETS = False
    print("WARNING: websockets not installed. Run: pip install websockets")

from .server import WorkflowServer
from .events import get_event_bus


class FrontendHandler(SimpleHTTPRequestHandler):
    """Serves the frontend files."""

    def __init__(self, *args, directory=None, **kwargs):
        self.frontend_dir = directory or Path(__file__).parent / "frontend"
        super().__init__(*args, directory=str(self.frontend_dir), **kwargs)

    def log_message(self, format, *args):
        # Suppress HTTP logs
        pass


def run_http_server(port: int):
    """Run HTTP server in a thread."""
    frontend_dir = Path(__file__).parent / "frontend"

    class Handler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=str(frontend_dir), **kwargs)

        def log_message(self, format, *args):
            pass

    server = HTTPServer(('localhost', port), Handler)
    server.serve_forever()


async def main(ws_port: int = 8765, http_port: int = 8766, no_browser: bool = False):
    """Run the visual workflow system."""

    if not HAS_WEBSOCKETS:
        print("ERROR: websockets package required.")
        print("Install with: pip install websockets")
        return

    # Start HTTP server in background thread
    http_thread = threading.Thread(target=run_http_server, args=(http_port,), daemon=True)
    http_thread.start()

    # Create workflow server
    server = WorkflowServer(port=ws_port)

    print()
    print("=" * 60)
    print("  CUBESQUARE VISUAL WORKFLOW")
    print("=" * 60)
    print()
    print(f"  Frontend:   http://localhost:{http_port}")
    print(f"  WebSocket:  ws://localhost:{ws_port}")
    print()
    print("  Features:")
    print("    - Node-based workflow editor")
    print("    - Real-time event streaming")
    print("    - 19 agents + Spheres + Tools")
    print("    - Flip, Dispatch, Dialogue")
    print()
    print("  Press Ctrl+C to stop")
    print("=" * 60)
    print()

    # Open browser
    if not no_browser:
        webbrowser.open(f"http://localhost:{http_port}")

    # Run WebSocket server
    async with ws_serve(server._handle_client, "localhost", ws_port):
        await asyncio.Future()  # Run forever


def cli():
    """CLI entry point."""
    parser = argparse.ArgumentParser(
        description="Cubesquare Visual Workflow - ComfyUI-style node editor"
    )
    parser.add_argument(
        "--port", type=int, default=8765,
        help="WebSocket port (default: 8765)"
    )
    parser.add_argument(
        "--http-port", type=int, default=8766,
        help="HTTP server port for frontend (default: 8766)"
    )
    parser.add_argument(
        "--no-browser", action="store_true",
        help="Don't open browser automatically"
    )

    args = parser.parse_args()

    try:
        asyncio.run(main(
            ws_port=args.port,
            http_port=args.http_port,
            no_browser=args.no_browser,
        ))
    except KeyboardInterrupt:
        print("\nShutting down...")


if __name__ == "__main__":
    cli()
