import argparse
import sys
import signal
import threading
from . import __version__
from .tunnel import TunnelClient


def main():
    parser = argparse.ArgumentParser(
        prog="dlab-ai-forward",
        description="Expose local LLM services (Ollama, LM Studio) to the cloud via WebSocket tunnel",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s --name demo --server https://ai.example.com --token <TOKEN_FROM_DASHBOARD>
    Connect with default settings (Ollama on port 11434, LM Studio on port 1234)

  %(prog)s --name my-node --server https://ai.example.com --token <TOKEN_FROM_DASHBOARD> --services ollama
    Expose only Ollama service

  %(prog)s --name demo --server https://ai.example.com --token <TOKEN_FROM_DASHBOARD> --verbose
    Enable debug logging

Note: Generate CLI tokens from the Dashboard UI before connecting.

For more information visit: https://github.com/dlab/ai-forward
"""
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}"
    )
    parser.add_argument(
        "--name",
        type=str,
        required=True,
        metavar="NAME",
        help="Unique tunnel identifier (e.g., 'demo', 'node-1')"
    )
    parser.add_argument(
        "--server",
        type=str,
        required=True,
        metavar="URL",
        help="Backend server URL (e.g., 'https://ai.example.com')"
    )
    parser.add_argument(
        "--token",
        type=str,
        required=True,
        metavar="TOKEN",
        help="Authentication token (generate from Dashboard UI)"
    )
    parser.add_argument(
        "--ollama-port",
        type=int,
        default=11434,
        metavar="PORT",
        help="Ollama local port (default: 11434)"
    )
    parser.add_argument(
        "--lmstudio-port",
        type=int,
        default=1234,
        metavar="PORT",
        help="LM Studio local port (default: 1234)"
    )
    parser.add_argument(
        "--services",
        type=str,
        nargs="+",
        choices=["ollama", "lmstudio"],
        default=["ollama", "lmstudio"],
        metavar="SERVICE",
        help="Services to expose: 'ollama', 'lmstudio', or both (default: ollama lmstudio)"
    )
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Enable debug logging"
    )
    parser.add_argument(
        "--insecure", "-k",
        action="store_true",
        help="Skip SSL certificate verification (for self-signed certs)"
    )

    args = parser.parse_args()

    tunnel = TunnelClient(
        name=args.name,
        server=args.server,
        token=args.token,
        ollama_port=args.ollama_port,
        lmstudio_port=args.lmstudio_port,
        services=args.services,
        verbose=args.verbose,
        insecure=args.insecure
    )

    # Handle shutdown signals
    def signal_handler(sig, frame):
        print("\nShutting down...")
        tunnel.stop()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    try:
        tunnel.run()
    except KeyboardInterrupt:
        print("\nShutting down...")
        tunnel.stop()
        sys.exit(0)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
