#!/usr/bin/env python3
"""Web UI server for accessibility mode on MageDok display.

Serves touch keyboard interface and displays STT transcripts.
Communicates with accessibility_mode_node via ROS2.
"""

import json
import threading
from http.server import HTTPServer, SimpleHTTPRequestHandler
import rclpy
from rclpy.node import Node
from std_msgs.msg import String


class AccessibilityUIHandler(SimpleHTTPRequestHandler):
    """HTTP request handler for accessibility UI."""

    def do_GET(self):
        """Serve HTML/CSS/JS files."""
        if self.path == "/" or self.path == "/index.html":
            self.path = "/accessibility.html"
        return super().do_GET()

    def log_message(self, format, *args):
        """Suppress request logging."""
        pass


class UIServerNode(Node):
    """ROS2 node for accessibility UI server."""

    def __init__(self, port=8000):
        super().__init__("accessibility_ui_server")

        self.port = port
        self.display_data = {}

        # Subscription to display updates
        self.create_subscription(
            String, "/accessibility/text_display", self._on_display_update, 10
        )

        # Publisher for keyboard input
        self.pub_keyboard = self.create_publisher(String, "/accessibility/keyboard_input", 10)

        # Start HTTP server in background thread
        self.server = HTTPServer(("0.0.0.0", port), AccessibilityUIHandler)
        self.server_thread = threading.Thread(target=self.server.serve_forever, daemon=True)
        self.server_thread.start()

        self.get_logger().info(f"Accessibility UI server listening on port {port}")

    def _on_display_update(self, msg: String) -> None:
        """Store display data for serving to web clients."""
        try:
            self.display_data = json.loads(msg.data)
        except json.JSONDecodeError:
            self.get_logger().error(f"Invalid display data JSON: {msg.data}")

    def send_keyboard_input(self, text: str) -> None:
        """Send keyboard input to accessibility mode node."""
        msg = String(data=text)
        self.pub_keyboard.publish(msg)


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


if __name__ == "__main__":
    main()
