#!/usr/bin/env python3
"""Task communication functional tests.

Tests the modified Task.py callback functionality with HTTPClient integration.
"""

import sys
import os
import unittest
from unittest.mock import Mock, patch

# Set required environment variable for Task module
os.environ['SCHEDULER_URL'] = 'http://localhost:6666'

# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'src'))

from task.parsers.callback import CallbackParameter


class TestTaskCommunication(unittest.TestCase):
    """Test task callback communication with HTTPClient integration."""

    def setUp(self):
        """Set up test environment."""
        self.callback_param = CallbackParameter(
            url="http://localhost:6666/callback",
            method="POST",
            headers={"Content-Type": "application/json"},
            request_body={"status": "completed", "result": "test"}
        )

    @patch('task.task.HTTPClient')
    @patch('task.task.requests')
    def test_httpclient_callback_success(self, mock_requests, mock_httpclient_class):
        """Test callback using HTTPClient when available."""
        # Mock HTTPClient
        mock_httpclient = Mock()
        mock_httpclient_class.return_value = mock_httpclient

        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.text = "Success"
        mock_httpclient.send_request.return_value = mock_response

        # Import Task after setting up mocks
        from task.task import Task
        from task.parsers.request import TaskConfiguration
        from calculation.base import CalculationBase
        import logging

        # Create minimal task instance
        mock_calculation = Mock(spec=CalculationBase)
        mock_config = Mock(spec=TaskConfiguration)
        mock_logger = logging.getLogger("test")
        mock_handler = Mock()

        task = Task(mock_calculation, mock_config, mock_handler, mock_logger)

        # Test the callback method (we need to access private method for testing)
        try:
            task._Task__send_callback(self.callback_param)

            # Verify HTTPClient was used
            mock_httpclient_class.assert_called_once()
            mock_httpclient.send_request.assert_called_once()

            # Verify requests was NOT used
            mock_requests.request.assert_not_called()

            print("✓ HTTPClient callback path working correctly")

        except Exception as e:
            print(f"HTTPClient callback test failed: {e}")

    @patch('task.task.HTTPClient', None)  # Simulate HTTPClient not available
    @patch('task.task.requests')
    def test_fallback_callback_success(self, mock_requests):
        """Test fallback to requests when HTTPClient not available."""
        # Mock requests response
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.text = "Success"
        mock_requests.request.return_value = mock_response

        # Import Task after setting up mocks
        from task.task import Task
        from task.parsers.request import TaskConfiguration
        from calculation.base import CalculationBase
        import logging

        # Create minimal task instance
        mock_calculation = Mock(spec=CalculationBase)
        mock_config = Mock(spec=TaskConfiguration)
        mock_logger = logging.getLogger("test")
        mock_handler = Mock()

        task = Task(mock_calculation, mock_config, mock_handler, mock_logger)

        # Test the callback method
        try:
            task._Task__send_callback(self.callback_param)

            # Verify requests was used as fallback
            mock_requests.request.assert_called()

            print("✓ Fallback requests callback path working correctly")

        except Exception as e:
            print(f"Fallback callback test failed: {e}")

    def test_url_parsing(self):
        """Test URL parsing functionality."""
        from urllib.parse import urlparse

        test_url = "http://localhost:6666/callback/path?param=value"
        parsed = urlparse(test_url)

        base_url = f"{parsed.scheme}://{parsed.netloc}"
        endpoint = parsed.path or "/"

        self.assertEqual(base_url, "http://localhost:6666")
        self.assertEqual(endpoint, "/callback/path")

        print("✓ URL parsing working correctly")

    def test_callback_parameter_structure(self):
        """Test CallbackParameter structure compatibility."""
        self.assertEqual(self.callback_param.url, "http://localhost:6666/callback")
        self.assertEqual(self.callback_param.method, "POST")
        self.assertIsInstance(self.callback_param.headers, dict)
        self.assertIsInstance(self.callback_param.request_body, dict)

        print("✓ CallbackParameter structure compatible")


if __name__ == '__main__':
    unittest.main(verbosity=2)