"""
LLUAV Python SDK - Async Usage Example (Enhanced)

This example demonstrates the asynchronous client with queue,
auto-reconnect, and periodic tasks.

Prerequisites:
    pip install websockets

Usage:
    python async_usage.py --host 192.168.1.100 --password your_password
"""

import argparse
import asyncio
import json
import sys

sys.path.insert(0, "../")
from lluav_sdk import LLUAVAsyncClient, LLUAVCommandError


async def main():
    parser = argparse.ArgumentParser(description="LLUAV SDK async usage example")
    parser.add_argument("--host", default="localhost", help="Drone IP address")
    parser.add_argument("--port", type=int, default=53001, help="WebSocket port")
    parser.add_argument("--password", default=None, help="Login password")
    args = parser.parse_args()

    client = LLUAVAsyncClient(
        host=args.host, port=args.port, password=args.password,
        auto_reconnect=True, heartbeat_interval=5.0,
    )

    try:
        await client.connect()
        print(f"Connected to {client.url}")

        # Register periodic task
        await client.add_periodic_task("sysinfo_poll", 3.0, "sysinfo")
        print("Registered periodic task: sysinfo_poll every 3s")

        # Concurrent queries
        ver, sysinfo, state = await asyncio.gather(
            client.get_version(),
            client.get_sysinfo(),
            client.get_state(),
        )
        print("\n--- Version ---")
        print(json.dumps(ver, indent=2, ensure_ascii=False))
        print("\n--- System Info ---")
        print(json.dumps(sysinfo, indent=2, ensure_ascii=False))

        print("\n--- Drone State (truncated) ---")
        state_str = json.dumps(state, indent=2, ensure_ascii=False)
        print(state_str[:1500] + "\n... [truncated]" if len(state_str) > 1500 else state_str)

        # Wait for periodic tasks
        print("\n--- Waiting 7 seconds for periodic tasks ---")
        await asyncio.sleep(7)

        await client.remove_periodic_task("sysinfo_poll")
        print("Removed periodic task: sysinfo_poll")

        print("\nDone.")

    except LLUAVCommandError as e:
        print(f"Command failed: {e} (ret={e.ret_code})")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        await client.disconnect()


if __name__ == "__main__":
    asyncio.run(main())
