"""
can_monitor.launch.py — Lightweight rosbridge server for CAN sensor dashboard (Issue #697)

Starts rosbridge_websocket on port 9090 with a whitelist limited to the five
topics consumed by can_monitor_panel.html:

  /saltybot/imu           sensor_msgs/Imu           — IMU attitude
  /saltybot/balance_state std_msgs/String (JSON)    — balance PID state
  /saltybot/barometer     std_msgs/String (JSON)    — pressure / temp / altitude
  /vesc/left/state        std_msgs/String (JSON)    — left VESC telemetry
  /vesc/right/state       std_msgs/String (JSON)    — right VESC telemetry

Usage:
  ros2 launch saltybot_bringup can_monitor.launch.py

  # Override port if needed:
  ros2 launch saltybot_bringup can_monitor.launch.py port:=9091

Verify:
  # From a browser on the same LAN:
  #   var ros = new ROSLIB.Ros({ url: 'ws://<jetson-ip>:9090' });
  #   ros.on('connection', () => console.log('connected'));
"""

import os
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node


# Topics exposed to the CAN monitor WebUI panel.
_TOPICS = [
    '/saltybot/imu',
    '/saltybot/balance_state',
    '/saltybot/barometer',
    '/vesc/left/state',
    '/vesc/right/state',
]

_TOPICS_GLOB = '[' + ', '.join(f'"{t}"' for t in _TOPICS) + ']'


def generate_launch_description():
    port_arg = DeclareLaunchArgument(
        'port',
        default_value='9090',
        description='WebSocket port for rosbridge (default 9090)',
    )

    rosbridge = Node(
        package='rosbridge_server',
        executable='rosbridge_websocket',
        name='rosbridge_websocket',
        parameters=[{
            'port':               LaunchConfiguration('port'),
            'host':               '0.0.0.0',
            'authenticate':       False,
            'max_message_size':   1000000,    # 1 MB — no large map payloads needed
            'topics_glob':        _TOPICS_GLOB,
            'services_glob':      '[]',
            'params_glob':        '[]',
            'unregister_timeout': 10.0,
            'fragment_timeout':   600,
            'delay_between_messages': 0,
        }],
        output='screen',
    )

    return LaunchDescription([port_arg, rosbridge])
