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

This example demonstrates:
  - Automatic login & auto-reconnect
  - Command queue with timeout management
  - Periodic task scheduler

Prerequisites:
    pip install websocket-client

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

import argparse
import json
import sys
import time

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


def main():
    parser = argparse.ArgumentParser(description="LLUAV SDK enhanced 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()

    # auto_reconnect=True (default), heartbeat_interval=5s (default)
    client = LLUAVClient(
        host=args.host,
        port=args.port,
        password=args.password,
        auto_reconnect=True,
        heartbeat_interval=5.0,
    )

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

        # Register a periodic task: fetch state every 2 seconds
        client.add_periodic_task("status_poll", 2.0, "state")
        print("Registered periodic task: status_poll every 2s")

        # 1. Get version and machine ID
        ver = client.get_version()
        print("\n--- Version ---")
        print(json.dumps(ver, indent=2, ensure_ascii=False))

        mid = client.get_machine_id()
        print("\n--- Machine ID ---")
        print(json.dumps(mid, indent=2, ensure_ascii=False))

        # 2. Get system info
        sysinfo = client.get_sysinfo()
        print("\n--- System Info ---")
        print(json.dumps(sysinfo, indent=2, ensure_ascii=False))

        # 3. Get drone state
        state = client.get_state()
        print("\n--- Drone State ---")
        state_str = json.dumps(state, indent=2, ensure_ascii=False)
        print(state_str[:2000] + "\n... [truncated]" if len(state_str) > 2000 else state_str)

        # 4. Preflight check
        print("\n--- Preflight Check ---")
        try:
            preflight = client.preflight_check()
            print(json.dumps(preflight, indent=2, ensure_ascii=False))
        except LLUAVCommandError as e:
            print(f"Preflight check error: {e}")

        # 5. Example: send command non-blocking (returns Future)
        print("\n--- Non-blocking command ---")
        future = client.send_cmd("state", block=False)
        # Do other work...
        result = future.result(timeout=10)
        print("Future result keys:", list(result.keys()))

        # 6. Let periodic tasks run for a few seconds
        print("\n--- Waiting 6 seconds for periodic tasks ---")
        time.sleep(6)

        # 7. Remove periodic task
        client.remove_periodic_task("status_poll")
        print("Removed periodic task: status_poll")

        # 8. Example: Takeoff (uncomment to execute)
        # print("\n--- Takeoff ---")
        # resp = client.takeoff()
        # print(json.dumps(resp, indent=2, ensure_ascii=False))

        print("\nDone.")

    except LLUAVCommandError as e:
        print(f"Command failed: {e} (ret={e.ret_code})")
        if e.response:
            print(f"Response: {json.dumps(e.response, indent=2)}")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        client.disconnect()


if __name__ == "__main__":
    main()
