import argparse
import os
import threading

from flownet.config import NodeRuntimeConfig
from flownet.platform.node_runtime import bootstrap_node_runtime


def main():
    os.environ.setdefault("FLOWNET_RUNTIME_ROLE", "node")
    parser = argparse.ArgumentParser(description="Start a Flownet node runtime.")
    parser.add_argument("--host", type=str, default="127.0.0.1", help="Host to bind the node runtime.")
    parser.add_argument("--port", type=int, required=True, help="Port to bind the node runtime.")
    parser.add_argument("--threads", type=int, default=4, help="Max worker threads for the node runtime.")
    parser.add_argument("--transport-mode", type=str, default="auto", help="Transport mode: auto|tcp|uds_prefer|hetero_auto.")
    parser.add_argument("--local-ipc-dir", type=str, default="/tmp/flownet", help="Directory for local IPC sockets.")
    parser.add_argument(
        "--transport-shm-threshold-bytes",
        type=int,
        default=262144,
        help="Payload size threshold to prefer SHM in hetero_auto mode.",
    )
    parser.add_argument(
        "--transport-shm-max-payload-bytes",
        type=int,
        default=67108864,
        help="Max payload bytes allowed for SHM transport.",
    )
    parser.add_argument(
        "--transport-backend-cooldown-seconds",
        type=float,
        default=1.0,
        help="Cooldown after backend failure before retrying same backend/address.",
    )
    parser.add_argument(
        "--transport-backend-cooldown-max-entries",
        type=int,
        default=4096,
        help="Max entries tracked in backend cooldown map.",
    )
    parser.add_argument(
        "--transport-backend-cooldown-cleanup-interval",
        type=int,
        default=128,
        help="Cleanup interval (send operations) for cooldown pruning.",
    )
    parser.add_argument("--node-id", type=str, default="default-node", help="Logical node id.")
    args = parser.parse_args()

    config = NodeRuntimeConfig(
        host=args.host,
        port=args.port,
        threads=args.threads,
        node_id=args.node_id,
        transport_mode=args.transport_mode,
        local_ipc_dir=args.local_ipc_dir,
        transport_shm_threshold_bytes=args.transport_shm_threshold_bytes,
        transport_shm_max_payload_bytes=args.transport_shm_max_payload_bytes,
        transport_backend_cooldown_seconds=args.transport_backend_cooldown_seconds,
        transport_backend_cooldown_max_entries=args.transport_backend_cooldown_max_entries,
        transport_backend_cooldown_cleanup_interval=args.transport_backend_cooldown_cleanup_interval,
    )
    bootstrap_node_runtime(config, node_id=args.node_id)
    print(f"[NodeRuntime Main] FlownetRuntime started at {args.host}:{args.port} with {args.threads} threads.")

    try:
        threading.Event().wait()
    except KeyboardInterrupt:
        print("[NodeRuntime Main] Shutdown requested. Exiting...")


if __name__ == "__main__":
    main()
