"""
Test suite for escape sequence decoding in terminal sessions.
"""
import pytest
from src.mcp_terminal.core.terminal.session import TerminalSession


class TestEscapeSequences:
    """Test escape sequence decoding."""

    def setup_method(self):
        """Create a terminal session for testing."""
        self.session = TerminalSession(rows=24, cols=80)

    def test_newline_escape(self):
        """Test \\n newline escape."""
        result = self.session._decode_escape_sequences("hello\\nworld")
        assert result == "hello\nworld", f"Expected 'hello\\nworld', got {repr(result)}"

    def test_carriage_return_escape(self):
        """Test \\r carriage return escape."""
        result = self.session._decode_escape_sequences("hello\\rworld")
        assert result == "hello\rworld", f"Expected 'hello\\rworld', got {repr(result)}"

    def test_crlf_escape(self):
        """Test \\r\\n Windows newline escape."""
        result = self.session._decode_escape_sequences("command\\r\\n")
        assert result == "command\r\n", f"Expected 'command\\r\\n', got {repr(result)}"

    def test_tab_escape(self):
        """Test \\t tab escape."""
        result = self.session._decode_escape_sequences("hello\\tworld")
        assert result == "hello\tworld", f"Expected 'hello\\tworld', got {repr(result)}"

    def test_hex_escape(self):
        """Test \\x## hexadecimal escape."""
        # \\x03 = Ctrl+C
        result = self.session._decode_escape_sequences("\\x03")
        assert result == "\x03", f"Expected '\\x03', got {repr(result)}"

        # \\x1b = ESC
        result = self.session._decode_escape_sequences("\\x1b")
        assert result == "\x1b", f"Expected '\\x1b', got {repr(result)}"

    def test_windows_path_preserved(self):
        """Test that Windows paths are preserved.

        When JSON deserializes "C:\\\\Users\\\\test", Python receives
        a string with double backslashes: 'C:\\\\Users\\\\test'
        """
        # Simulate how JSON sends paths with escaped backslashes
        path = "C:\\\\Users\\\\test\\\\file.exe"
        expected = "C:\\Users\\test\\file.exe"  # Should decode to single backslashes
        result = self.session._decode_escape_sequences(path)
        assert result == expected, f"Windows path should decode to single backslashes, got {repr(result)}"

    def test_windows_path_with_newline(self):
        """Test Windows path followed by newline.

        JSON sends: "C:\\\\Users\\\\test\\\\file.exe\\r\\n"
        Python receives: 'C\\\\Users\\\\test\\\\file.exe\\r\\n' (backslashes are literal)
        """
        input_str = "C:\\\\Users\\\\test\\\\file.exe\\r\\n"
        expected = "C:\\Users\\test\\file.exe\r\n"
        result = self.session._decode_escape_sequences(input_str)
        assert result == expected, f"Expected {repr(expected)}, got {repr(result)}"

    def test_double_backslash(self):
        """Test \\\\ (escaped backslash)."""
        result = self.session._decode_escape_sequences("path\\\\to\\\\file")
        assert result == "path\\to\\file", f"Expected 'path\\to\\file', got {repr(result)}"

    def test_unknown_escape_preserved(self):
        """Test that unknown escape sequences are preserved."""
        # \\q is not a known escape, should keep backslash
        result = self.session._decode_escape_sequences("\\q")
        assert result == "\\q", f"Unknown escape should be preserved, got {repr(result)}"

    def test_mixed_escapes(self):
        """Test multiple escape types in one string."""
        input_str = "echo hello\\nworld\\r\\n"
        expected = "echo hello\nworld\r\n"
        result = self.session._decode_escape_sequences(input_str)
        assert result == expected, f"Expected {repr(expected)}, got {repr(result)}"

    def test_ctrl_c_command(self):
        """Test Ctrl+C character."""
        result = self.session._decode_escape_sequences("\\x03")
        assert result == "\x03", "Ctrl+C should be decoded correctly"

    def test_vim_exit_sequence(self):
        """Test vim exit sequence (ESC :wq)."""
        input_str = "\\x1b:wq\\r\\n"
        expected = "\x1b:wq\r\n"
        result = self.session._decode_escape_sequences(input_str)
        assert result == expected, f"Vim exit sequence failed: {repr(result)}"

    def test_lynx_command_with_path(self):
        """Test the exact command that was failing.

        JSON sends backslashes escaped, so we receive double backslashes.
        """
        input_str = "C:\\\\Users\\\\Usuario\\\\scoop\\\\shims\\\\lynx.exe https://example.com\\r\\n"
        expected = "C:\\Users\\Usuario\\scoop\\shims\\lynx.exe https://example.com\r\n"
        result = self.session._decode_escape_sequences(input_str)
        assert result == expected, f"Lynx command failed: {repr(result)}"

    def test_empty_string(self):
        """Test empty string."""
        result = self.session._decode_escape_sequences("")
        assert result == "", "Empty string should return empty string"

    def test_no_escapes(self):
        """Test string with no escape sequences."""
        input_str = "plain text without escapes"
        result = self.session._decode_escape_sequences(input_str)
        assert result == input_str, "Plain text should be unchanged"

    def test_invalid_hex_escape(self):
        """Test invalid hex escape sequence."""
        # \\xZZ is not valid hex, should preserve backslash
        result = self.session._decode_escape_sequences("\\xZZ")
        assert result == "\\xZZ", f"Invalid hex should be preserved, got {repr(result)}"

    def test_incomplete_hex_escape(self):
        """Test incomplete hex escape at end of string."""
        result = self.session._decode_escape_sequences("test\\x0")
        assert result == "test\\x0", "Incomplete hex should be preserved"


if __name__ == "__main__":
    # Run tests
    import sys
    pytest.main([__file__, "-v"] + sys.argv[1:])
