#!/usr/bin/env python3
"""
QR 识别 → TTS 语音播报桥接节点
订阅 qr_results，调用 /tts/speak 服务
"""
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from origincar_msg.srv import Speak


class QrTtsBridge(Node):
    def __init__(self):
        super().__init__('qr_tts_bridge')

        # TTS 服务客户端
        self.tts_client = self.create_client(Speak, '/tts/speak')
        while not self.tts_client.wait_for_service(timeout_sec=5.0):
            self.get_logger().info('Waiting for TTS service...')
        self.get_logger().info('TTS service connected')

        # 订阅 QR 识别结果
        self.sub = self.create_subscription(
            String, 'qr_results', self.callback, 10)

        self.get_logger().info('QR-TTS Bridge ready, listening on qr_results')

    def callback(self, msg):
        text = msg.data.strip()
        if not text:
            return

        self.get_logger().info(f'QR result: {text}')

        if not self.tts_client.service_is_ready():
            self.get_logger().warning('TTS service not available')
            return

        req = Speak.Request()
        req.text = text
        future = self.tts_client.call_async(req)
        future.add_done_callback(self._tts_done_callback)

    def _tts_done_callback(self, future):
        try:
            resp = future.result()
            if not resp.success:
                self.get_logger().warning(f'TTS failed: {resp.message}')
        except Exception as e:
            self.get_logger().error(f'TTS call error: {e}')


def main(args=None):
    rclpy.init(args=args)
    node = QrTtsBridge()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()
