#!/usr/bin/env python3
"""Test RPC communication between nodes.

This script sends an RPC request to a remote Styrene daemon and
waits for a response.

Usage:
    python scripts/test_rpc.py <destination_identity_hash>

Example:
    python scripts/test_rpc.py 698f2232d4ddab456ca11f38c8bb8a90
"""

import asyncio
import logging
import sys

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)


async def main(destination: str) -> None:
    """Send RPC request to destination."""
    from styrene.services.app_lifecycle import StyreneLifecycle
    from styrene.services.config import load_config
    from styrene.services.lxmf_service import get_lxmf_service
    from styrene.services.rpc_client import RPCClient

    # Load config and initialize
    config = load_config()
    config.reticulum.hub_enabled = False

    lifecycle = StyreneLifecycle(config)
    if not lifecycle.initialize():
        logger.error("Failed to initialize")
        sys.exit(1)

    logger.info("Services initialized")

    # Wait for announces to propagate
    logger.info("Waiting 5 seconds for mesh announces...")
    await asyncio.sleep(5)

    # Create RPC client
    lxmf_service = get_lxmf_service()
    rpc_client = RPCClient(lxmf_service)

    logger.info(f"Sending status_request to {destination}")

    try:
        # Try status request with 30 second timeout
        response = await rpc_client.call_status(destination, timeout=30.0)

        logger.info("=== STATUS RESPONSE ===")
        logger.info(f"Uptime: {response.format_uptime()}")
        logger.info(f"IP: {response.ip}")
        logger.info(f"Services: {response.services}")
        logger.info(f"Disk: {response.format_disk_usage()}")

    except Exception as e:
        logger.error(f"RPC call failed: {e}")

    # Cleanup
    lifecycle.shutdown()


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <destination_identity_hash>")
        sys.exit(1)

    destination = sys.argv[1]
    asyncio.run(main(destination))
