#!/usr/bin/env python3
"""Deaf/accessibility mode node for SaltyBot.

Integrates speech-to-text (Whisper), touch keyboard input, and TTS output.
Provides accessible interface for hearing-impaired users via MageDok 7in display.

Subscribed topics:
  /social/speech/transcript (SpeechTranscript) - STT from speech pipeline
  /accessibility/keyboard_input (String) - Touch keyboard input

Published topics:
  /accessibility/text_display (String) - Text to display on screen
  /social/conversation/request (ConversationRequest) - TTS request
  /accessibility/mode_state (Bool) - Accessibility mode enabled state
"""

import json
import rclpy
from rclpy.node import Node
from std_msgs.msg import String, Bool
from saltybot_social_msgs.msg import SpeechTranscript, ConversationRequest


class AccessibilityModeNode(Node):
    """Deaf/accessibility mode coordinator."""

    def __init__(self):
        super().__init__("accessibility_mode")

        # Parameters
        self.declare_parameter("enabled", True)
        self.declare_parameter("max_display_history", 10)
        self.declare_parameter("auto_tts", True)
        self.declare_parameter("keyboard_enabled", True)
        self.declare_parameter("display_timeout_s", 30.0)

        self.enabled = self.get_parameter("enabled").value
        self.max_history = self.get_parameter("max_display_history").value
        self.auto_tts = self.get_parameter("auto_tts").value
        self.keyboard_enabled = self.get_parameter("keyboard_enabled").value
        self.display_timeout = self.get_parameter("display_timeout_s").value

        # State
        self.display_history = []
        self.last_transcript = ""
        self.keyboard_buffer = ""

        # Subscriptions
        self.create_subscription(
            SpeechTranscript,
            "/social/speech/transcript",
            self._on_transcript,
            10,
        )
        self.create_subscription(
            String, "/accessibility/keyboard_input", self._on_keyboard_input, 10
        )

        # Publishers
        self.pub_display = self.create_publisher(String, "/accessibility/text_display", 10)
        self.pub_tts = self.create_publisher(
            ConversationRequest, "/social/conversation/request", 10
        )
        self.pub_state = self.create_publisher(Bool, "/accessibility/mode_state", 10)

        # Publish initial state
        state_msg = Bool(data=self.enabled)
        self.pub_state.publish(state_msg)

        self.get_logger().info(
            f"Accessibility mode initialized: "
            f"enabled={self.enabled}, auto_tts={self.auto_tts}, "
            f"keyboard={self.keyboard_enabled}"
        )

    def _on_transcript(self, msg: SpeechTranscript) -> None:
        """Handle incoming speech-to-text transcript."""
        if not self.enabled:
            return

        transcript = msg.text.strip()
        if not transcript:
            return

        self.last_transcript = transcript
        self.keyboard_buffer = ""  # Clear keyboard buffer on new voice input

        # Add to display history
        self.display_history.append({"type": "stt", "text": transcript, "final": msg.is_final})
        if len(self.display_history) > self.max_history:
            self.display_history.pop(0)

        # Update display
        self._update_display()

        # Auto-speak back for confirmation (optional)
        if self.auto_tts and msg.is_final:
            self._send_tts_confirmation(transcript)

        self.get_logger().info(f"STT: {transcript}")

    def _on_keyboard_input(self, msg: String) -> None:
        """Handle touch keyboard input."""
        if not self.enabled or not self.keyboard_enabled:
            return

        text = msg.data.strip()

        if text == "[CLEAR]":
            # Clear keyboard buffer
            self.keyboard_buffer = ""
        elif text == "[SEND]":
            # Send keyboard text as TTS request
            if self.keyboard_buffer:
                self._send_tts_request(self.keyboard_buffer)
                self.display_history.append(
                    {"type": "keyboard", "text": self.keyboard_buffer, "final": True}
                )
                if len(self.display_history) > self.max_history:
                    self.display_history.pop(0)
                self.keyboard_buffer = ""
        elif text == "[BACKSPACE]":
            # Remove last character
            self.keyboard_buffer = self.keyboard_buffer[:-1]
        elif text == "[SPACE]":
            # Add space
            self.keyboard_buffer += " "
        else:
            # Regular character input
            self.keyboard_buffer += text

        # Update display
        self._update_display()
        self.get_logger().info(f"Keyboard: {self.keyboard_buffer}")

    def _update_display(self) -> None:
        """Update text display with history and keyboard buffer."""
        display_data = {
            "history": self.display_history,
            "keyboard_buffer": self.keyboard_buffer,
            "mode": "accessibility",
            "timestamp": self.get_clock().now().to_msg(),
        }

        msg = String(data=json.dumps(display_data))
        self.pub_display.publish(msg)

    def _send_tts_confirmation(self, transcript: str) -> None:
        """Send confirmation TTS."""
        msg = ConversationRequest()
        msg.text = f"You said: {transcript}"
        msg.language = "en"
        self.pub_tts.publish(msg)

    def _send_tts_request(self, text: str) -> None:
        """Send custom TTS request."""
        msg = ConversationRequest()
        msg.text = text
        msg.language = "en"
        self.pub_tts.publish(msg)


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


if __name__ == "__main__":
    main()
