import pytest
from unittest.mock import Mock, patch
from valenceai import ValenceClient
from valenceai.exceptions import ValenceSDKException


class TestRateLimitAPI:

    @patch('valenceai.config.VALENCE_API_KEY', 'test_api_key')
    def test_client_has_rate_limit_property(self):
        """Test that ValenceClient has rate_limit property."""
        client = ValenceClient(api_key="test_key")
        assert hasattr(client, 'rate_limit')

    @patch('valenceai.rate_limit.requests.get')
    @patch('valenceai.config.VALENCE_API_KEY', 'test_key')
    def test_get_status_success(self, mock_get):
        """Test successful rate limit status retrieval."""
        # Mock successful response
        mock_response = Mock()
        mock_response.json.return_value = {
            "limits": {
                "second": {"limit": 10, "remaining": 8, "reset": 1234567890},
                "minute": {"limit": 100, "remaining": 95, "reset": 1234567890},
                "hour": {"limit": 1000, "remaining": 950, "reset": 1234567890},
                "day": {"limit": 10000, "remaining": 9500, "reset": 1234567890}
            },
            "current_usage": {
                "second": 2,
                "minute": 5,
                "hour": 50,
                "day": 500
            }
        }
        mock_response.raise_for_status.return_value = None
        mock_get.return_value = mock_response

        client = ValenceClient(api_key="test_key")
        result = client.rate_limit.get_status()

        # Verify the request was made correctly
        mock_get.assert_called_once()
        call_args = mock_get.call_args

        # Check URL uses new v1 endpoint
        assert '/v1/rate-limit/status' in call_args[0][0]
        # Check headers
        assert call_args[1]['headers'] == {"x-api-key": 'test_key'}

        # Check response
        assert "limits" in result
        assert "current_usage" in result
        assert result["limits"]["second"]["remaining"] == 8

    @patch('valenceai.rate_limit.requests.get')
    @patch('valenceai.config.VALENCE_API_KEY', 'test_key')
    def test_get_health_success(self, mock_get):
        """Test successful health check."""
        # Mock successful response
        mock_response = Mock()
        mock_response.json.return_value = {
            "status": "healthy",
            "timestamp": 1234567890
        }
        mock_response.raise_for_status.return_value = None
        mock_get.return_value = mock_response

        client = ValenceClient(api_key="test_key")
        result = client.rate_limit.get_health()

        # Verify the request was made correctly
        mock_get.assert_called_once()
        call_args = mock_get.call_args

        # Check URL uses new v1 endpoint
        assert '/v1/rate-limit/health' in call_args[0][0]
        # Check headers
        assert call_args[1]['headers'] == {"x-api-key": 'test_key'}

        # Check response
        assert result["status"] == "healthy"

    @patch('valenceai.rate_limit.requests.get')
    @patch('valenceai.config.VALENCE_API_KEY', 'test_key')
    def test_get_status_http_error(self, mock_get):
        """Test rate limit status with HTTP error."""
        mock_response = Mock()
        mock_response.raise_for_status.side_effect = Exception("HTTP 500 Error")
        mock_get.return_value = mock_response

        client = ValenceClient(api_key="test_key")

        with pytest.raises(Exception, match="HTTP 500 Error"):
            client.rate_limit.get_status()

    @patch('valenceai.rate_limit.requests.get')
    @patch('valenceai.config.VALENCE_API_KEY', 'test_key')
    def test_get_health_http_error(self, mock_get):
        """Test health check with HTTP error."""
        mock_response = Mock()
        mock_response.raise_for_status.side_effect = Exception("HTTP 503 Error")
        mock_get.return_value = mock_response

        client = ValenceClient(api_key="test_key")

        with pytest.raises(Exception, match="HTTP 503 Error"):
            client.rate_limit.get_health()

    @patch('valenceai.rate_limit.requests.get')
    @patch('valenceai.config.VALENCE_API_KEY', 'test_key')
    def test_uses_custom_base_url(self, mock_get):
        """Test that rate limit API uses custom base URL when provided."""
        mock_response = Mock()
        mock_response.json.return_value = {"status": "healthy"}
        mock_response.raise_for_status.return_value = None
        mock_get.return_value = mock_response

        client = ValenceClient(api_key='test_key', base_url='https://custom.example.com')
        client.rate_limit.get_health()

        call_args = mock_get.call_args
        assert 'https://custom.example.com/v1/rate-limit/health' in call_args[0][0]
