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')
config_dir = os.path.join(share_dir, 'configs/launch_configs/detect_service.json')
with open(config_dir, "r") as f:
    configs = json.load(f)

def generate_launch_description():
    args_detect = [
        DeclareLaunchArgument('checkpoint_name', default_value=configs['checkpoint_name']),
        DeclareLaunchArgument('output_boxes', default_value=configs['output_boxes']),
        DeclareLaunchArgument('output_masks', default_value=configs['output_masks']),
        DeclareLaunchArgument('set_confidence', default_value=configs['set_confidence']),
        DeclareLaunchArgument('classes', default_value=configs['classes']),
    ]

    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_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),
    ])
