# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Migrated from Gazebo Classic to Gazebo Sim (gz-sim / Harmonic)

import os

from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node


def generate_launch_description():
    # Pre-resolve package paths (portable across environments)
    turtlebot3_gazebo_share = get_package_share_directory('turtlebot3_gazebo')

    # Get the SDF file
    TURTLEBOT3_MODEL = os.environ['TURTLEBOT3_MODEL']
    model_folder = 'turtlebot3_' + TURTLEBOT3_MODEL
    sdf_path = os.path.join(
        turtlebot3_gazebo_share,
        'models',
        model_folder,
        'model_gz.sdf'
    )

    # Bridge configuration YAML (avoids --ros-args -p @ parsing issue)
    bridge_config_path = os.path.join(
        turtlebot3_gazebo_share, 'config', 'turtlebot3_gz_bridge.yaml'
    )

    # Launch configuration variables specific to simulation
    x_pose = LaunchConfiguration('x_pose', default='3.0')
    y_pose = LaunchConfiguration('y_pose', default='3.0')

    # Declare the launch arguments
    declare_x_position_cmd = DeclareLaunchArgument(
        'x_pose', default_value='3.0',
        description='Specify namespace of the robot')

    declare_y_position_cmd = DeclareLaunchArgument(
        'y_pose', default_value='3.0',
        description='Specify namespace of the robot')

    start_gz_spawner_cmd = Node(
        package='ros_gz_sim',
        executable='create',
        arguments=[
            '-name', TURTLEBOT3_MODEL,
            '-file', sdf_path,
            '-x', x_pose,
            '-y', y_pose,
            '-z', '0.03'
        ],
        output='screen',
    )

    start_bridge_cmd = Node(
        package='ros_gz_bridge',
        executable='bridge_node',
        parameters=[{
            'config_file': bridge_config_path,
            'use_sim_time': True,
        }],
        output='screen'
    )

    ld = LaunchDescription()

    ld.add_action(declare_x_position_cmd)
    ld.add_action(declare_y_position_cmd)
    ld.add_action(start_gz_spawner_cmd)
    ld.add_action(start_bridge_cmd)

    return ld
