"""Tests for clear console utility."""

import platform
from unittest.mock import patch


def test_clear_import():
    """Test that clear module can be imported."""
    from pytola.system.clear.cli import main

    assert callable(main)


def test_clear_screen_function_exists():
    """Test that clear_screen function exists."""
    from pytola.system.clear.cli import clear_screen

    assert callable(clear_screen)


def test_platform_detection():
    """Test platform detection logic."""
    from pytola.system.clear.cli import IS_WINDOWS

    # Verify IS_WINDOWS matches actual platform
    actual_is_windows = platform.system() == "Windows"
    assert IS_WINDOWS == actual_is_windows


@patch("pytola.system.clear.cli.subprocess.run")
def test_clear_screen_windows(mock_subprocess):
    """Test clear_screen on Windows (mocked)."""
    from pytola.system.clear.cli import clear_screen

    with patch("pytola.system.clear.cli.IS_WINDOWS", True):
        clear_screen()
        # Should call cmd.exe with cls command
        mock_subprocess.assert_called_with(["cmd", "/c", "cls"], check=True)


@patch("pytola.system.clear.cli.subprocess.run")
def test_clear_screen_unix(mock_subprocess):
    """Test clear_screen on Unix-like systems (mocked)."""
    from pytola.system.clear.cli import clear_screen

    with patch("pytola.system.clear.cli.IS_WINDOWS", False):
        clear_screen()
        # Should call clear command
        mock_subprocess.assert_called_with(["clear"], check=True)


def test_main_function():
    """Test that main function runs without errors."""
    from pytola.system.clear.cli import main

    # Mock sys.argv to avoid argparse issues
    with patch("sys.argv", ["clear"]):
        result = main()
        # Should return 0 on success
        assert result == 0


def test_main_with_debug():
    """Test main function with debug flag."""
    from pytola.system.clear.cli import main

    with patch("sys.argv", ["clear", "--debug"]):
        result = main()
        assert result == 0


def test_ansi_escape_code_output():
    """Test that ANSI escape codes are printed."""
    # Capture stdout
    import io
    import sys

    from pytola.system.clear.cli import clear_screen

    captured_output = io.StringIO()
    old_stdout = sys.stdout
    sys.stdout = captured_output

    try:
        with patch("pytola.system.clear.cli.subprocess.run"):
            clear_screen()

        output = captured_output.getvalue()
        # Should contain ANSI escape codes
        assert "\033[2J" in output
        assert "\033[H" in output
    finally:
        sys.stdout = old_stdout
