from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import DeclareLaunchArgument, OpaqueFunction
from launch.substitutions import LaunchConfiguration

import os
import ast
import json
from ament_index_python.packages import get_package_share_directory


share_dir = get_package_share_directory('vision_detect')


def generate_launch_description():
    args_detect = [
        DeclareLaunchArgument('checkpoint_name', default_value='yolo11s-seg.pt'),
        DeclareLaunchArgument('output_boxes', default_value='True'),
        DeclareLaunchArgument('output_masks', default_value='False'),
        DeclareLaunchArgument('set_confidence', default_value='0.25'),
        DeclareLaunchArgument('classes', default_value='None'),
        DeclareLaunchArgument('classes', default_value='None')
    ]

    def create_detect_node(context):
        checkpoint = LaunchConfiguration('checkpoint_name').perform(context)
        output_boxes = LaunchConfiguration('output_boxes').perform(context)
        output_masks = LaunchConfiguration('output_masks').perform(context)
        conf = LaunchConfiguration('set_confidence').perform(context)
        classes = LaunchConfiguration('classes').perform(context)

        return [
            Node(
                package='vision_detect',
                executable='detect_box_service_node',
                parameters=[{
                    'checkpoint_name': checkpoint,
                    'output_boxes': output_boxes.lower() == 'true',
                    'output_masks': output_masks.lower() == 'true',
                    'set_confidence': float(conf),
                    'classes': classes,
                }]
            )
        ]

    return LaunchDescription(args_detect + [
        OpaqueFunction(function=create_detect_node),
    ])
