"""meshnet-relay CLI entry point."""

from __future__ import annotations

import argparse
import logging
import time
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="meshnet-relay",
        description="Meshnet NAT-traversal relay and gossip hub",
    )
    parser.add_argument("--host", default="0.0.0.0", help="Interface to bind")
    parser.add_argument("--port", type=int, default=8765, help="WebSocket port")
    parser.add_argument("--cert", metavar="PATH", help="TLS certificate (PEM)")
    parser.add_argument("--key", metavar="PATH", help="TLS private key (PEM)")
    parser.add_argument("--max-peers", type=int, default=500, help="Max concurrent peers")
    parser.add_argument("--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"])

    args = parser.parse_args()
    logging.basicConfig(
        level=getattr(logging, args.log_level),
        format="%(asctime)s  %(levelname)-8s  %(name)s  %(message)s",
    )

    from .server import RelayServer

    ssl_cert = Path(args.cert) if args.cert else None
    ssl_key = Path(args.key) if args.key else None

    server = RelayServer(
        host=args.host,
        port=args.port,
        ssl_cert=ssl_cert,
        ssl_key=ssl_key,
        max_peers=args.max_peers,
    )
    port = server.start()
    scheme = "wss" if ssl_cert else "ws"
    print(f"meshnet-relay listening on {scheme}://{args.host}:{port}", flush=True)
    print("  /ws             gossip PubSub", flush=True)
    print("  /relay/<id>     circuit relay to peer", flush=True)
    print("  /health         health check", flush=True)
    print("  /v1/peers       peer list", flush=True)
    print("Press Ctrl-C to stop.", flush=True)

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopping relay…", flush=True)
        server.stop()


if __name__ == "__main__":
    main()
