#!/usr/bin/env python3

import argparse
import sys
import qi


def main():
    parser = argparse.ArgumentParser(description="Get or set a NAO robot's volume.")
    parser.add_argument("--ip", required=True, help="NAO IP address")
    parser.add_argument("--port", type=int, default=9559, help="NAOqi port (default: 9559)")
    parser.add_argument(
        "--set",
        type=int,
        metavar="VOLUME",
        help="Set volume (0-100)"
    )

    args = parser.parse_args()

    try:
        session = qi.Session()
        session.connect(f"tcp://{args.ip}:{args.port}")
    except RuntimeError as e:
        print(f"Failed to connect: {e}", file=sys.stderr)
        sys.exit(1)

    audio = session.service("ALAudioDevice")

    if args.set is not None:
        volume = max(0, min(100, args.set))
        audio.setOutputVolume(volume)
        print(f"Volume set to {volume}%")

    print(f"Current volume: {audio.getOutputVolume()}%")


if __name__ == "__main__":
    main()
