"""
Tests for GateWay CLI.

Tests the argparse-based CLI using direct function calls.
"""

import importlib
import importlib.util
import io
import sys
from contextlib import redirect_stdout
from unittest.mock import Mock, patch

import pytest

# Get the actual auth module (not the function)

_auth_module_spec = importlib.util.find_spec('verlex_server.gateway.client.auth')
_auth_module = importlib.util.module_from_spec(_auth_module_spec)
_auth_module_spec.loader.exec_module(_auth_module)


class TestCLI:
    """Tests for CLI commands."""

    def test_version_command(self):
        """Test version command."""
        from verlex_server.gateway import __version__
        from verlex_server.gateway.cli import cmd_version

        # Capture output
        captured = io.StringIO()
        with redirect_stdout(captured):
            result = cmd_version(Mock())

        assert result == 0
        output = captured.getvalue()
        assert "GateWay" in output
        assert __version__ in output

    def test_whoami_not_logged_in(self):
        """Test whoami when not logged in."""
        # The whoami function is imported inside cmd_whoami, so we patch
        # at the source module level
        original = _auth_module.whoami
        try:
            _auth_module.whoami = Mock(return_value=None)
            # Also patch in sys.modules to ensure import picks it up
            sys.modules['verlex_server.gateway.client.auth'] = _auth_module

            from verlex_server.gateway.cli import cmd_whoami
            args = Mock()
            result = cmd_whoami(args)

            # Should return error code when not logged in
            assert result == 1
        finally:
            _auth_module.whoami = original

    def test_whoami_logged_in(self):
        """Test whoami when logged in."""
        original = _auth_module.whoami
        try:
            _auth_module.whoami = Mock(return_value=Mock(
                user_id="user_123",
                email="test@example.com",
            ))
            sys.modules['verlex_server.gateway.client.auth'] = _auth_module

            from verlex_server.gateway.cli import cmd_whoami
            args = Mock()
            result = cmd_whoami(args)

            # Should succeed
            assert result == 0
        finally:
            _auth_module.whoami = original

    def test_main_help(self):
        """Test main function with help."""
        from verlex_server.gateway.cli import main

        # Test with --help should exit with 0
        with patch.object(sys, 'argv', ['gateway', '--help']):
            with pytest.raises(SystemExit) as exc_info:
                main()
            assert exc_info.value.code == 0

    def test_prices_command_structure(self):
        """Test prices command exists and is callable."""
        from verlex_server.gateway.cli import cmd_prices

        assert callable(cmd_prices)

    def test_jobs_command_structure(self):
        """Test jobs command exists and is callable."""
        from verlex_server.gateway.cli import cmd_jobs

        assert callable(cmd_jobs)

    def test_providers_command(self):
        """Test providers command."""
        from verlex_server.gateway.cli import cmd_providers

        args = Mock()
        args.json = False

        # Should run without error
        result = cmd_providers(args)
        assert result == 0


class TestCLIRun:
    """Tests for CLI run command."""

    def test_run_command_no_file(self):
        """Test run command without file."""
        original_get_session = _auth_module.get_session
        original_auth = _auth_module.auth
        try:
            # Create a proper mock session with required attributes
            mock_session = Mock()
            mock_session.mode = "F"
            mock_session.priority = False
            mock_session.flexible = True
            _auth_module.get_session = Mock(return_value=mock_session)
            _auth_module.auth = Mock(return_value=mock_session)
            sys.modules['verlex_server.gateway.client.auth'] = _auth_module

            from verlex_server.gateway.cli import cmd_run

            args = Mock()
            args.script = "nonexistent_script_12345.py"
            args.mode = "F"
            args.priority = None
            args.flexible = None
            args.gpu = None
            args.memory = None
            args.cpu = None
            args.async_mode = False
            args.json = False
            args.timeout = None

            # Should fail because file doesn't exist
            result = cmd_run(args)
            assert result == 1
        finally:
            _auth_module.get_session = original_get_session
            _auth_module.auth = original_auth


class TestCLIInteract:
    """Tests for CLI interact command."""

    def test_interact_command_exists(self):
        """Test that interact command handler exists."""
        from verlex_server.gateway.cli import cmd_interact

        # Command should be importable
        assert callable(cmd_interact)


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