#!/usr/bin/env python3
"""
enrollment_cli.py -- CLI tool for enrolling persons via the /social/enroll service.

Usage:
    ros2 run saltybot_social_face enrollment_cli -- --name Alice --mode face --samples 10
"""

import argparse
import sys

import rclpy
from rclpy.node import Node

from saltybot_social_msgs.srv import EnrollPerson


class EnrollmentCLI(Node):
    """Simple CLI node that calls the EnrollPerson service."""

    def __init__(self, name: str, mode: str, n_samples: int):
        super().__init__('enrollment_cli')
        self._client = self.create_client(EnrollPerson, '/social/enroll')

        self.get_logger().info('Waiting for /social/enroll service...')
        if not self._client.wait_for_service(timeout_sec=10.0):
            self.get_logger().error('Service /social/enroll not available.')
            return

        request = EnrollPerson.Request()
        request.name = name
        request.mode = mode
        request.n_samples = n_samples

        self.get_logger().info(
            'Enrolling "%s" (mode=%s, samples=%d)...', name, mode, n_samples)

        future = self._client.call_async(request)
        rclpy.spin_until_future_complete(self, future, timeout_sec=120.0)

        if future.result() is not None:
            result = future.result()
            if result.success:
                self.get_logger().info(
                    'Enrollment successful: person_id=%d, %s',
                    result.person_id, result.message)
            else:
                self.get_logger().error(
                    'Enrollment failed: %s', result.message)
        else:
            self.get_logger().error('Enrollment service call timed out or failed.')


def main(args=None):
    """Entry point for enrollment CLI."""
    parser = argparse.ArgumentParser(description='Enroll a person for face recognition.')
    parser.add_argument('--name', type=str, required=True,
                        help='Name of the person to enroll.')
    parser.add_argument('--mode', type=str, default='face',
                        choices=['face', 'voice', 'both'],
                        help='Enrollment mode (default: face).')
    parser.add_argument('--samples', type=int, default=10,
                        help='Number of face samples to collect (default: 10).')

    # Parse only known args so ROS2 remapping args pass through
    parsed, remaining = parser.parse_known_args(args=sys.argv[1:])

    rclpy.init(args=remaining)
    node = EnrollmentCLI(parsed.name, parsed.mode, parsed.samples)
    try:
        pass  # Node does all work in __init__
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()
