"""
test_launch_full_stack.py — Launch testing for full ROS2 stack integration.

Uses launch_testing to verify the complete system launches correctly.
"""

import os
import pytest
from ament_index_python.packages import get_package_share_directory


class TestFullStackSystemIntegrity:
    """Tests for overall system integrity during integration."""

    def test_launch_file_syntax_valid(self):
        """Verify full_stack.launch.py has valid Python syntax."""
        pkg_dir = get_package_share_directory("saltybot_bringup")
        launch_file = os.path.join(pkg_dir, "launch", "full_stack.launch.py")
        try:
            with open(launch_file, 'r') as f:
                code = f.read()
            compile(code, launch_file, 'exec')
            assert True, "Launch file syntax is valid"
        except SyntaxError as e:
            pytest.fail(f"Launch file has syntax error: {e}")

    def test_launch_dependencies_installed(self):
        """Verify all launch file dependencies are installed."""
        try:
            required_packages = [
                'saltybot_bringup',
                'saltybot_description',
                'saltybot_bridge',
            ]
            for pkg in required_packages:
                dir_path = get_package_share_directory(pkg)
                assert dir_path and os.path.isdir(dir_path), f"Package {pkg} not found"
            assert True, "All required packages installed"
        except Exception as e:
            pytest.skip(f"Package check skipped: {e}")


class TestComponentLaunchSequence:
    """Tests for launch sequence and timing."""

    def test_launch_sequence_timing(self):
        """Verify launch sequence timing is reasonable."""
        pkg_dir = get_package_share_directory("saltybot_bringup")
        launch_file = os.path.join(pkg_dir, "launch", "full_stack.launch.py")
        with open(launch_file, 'r') as f:
            content = f.read()
        timer_count = content.count("TimerAction")
        assert timer_count > 5, "Launch should have multiple timed launch groups"

    def test_conditional_launch_logic(self):
        """Verify conditional launch logic for optional components."""
        pkg_dir = get_package_share_directory("saltybot_bringup")
        launch_file = os.path.join(pkg_dir, "launch", "full_stack.launch.py")
        with open(launch_file, 'r') as f:
            content = f.read()
        assert "IfCondition" in content or "enable_" in content


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])
