#!/usr/bin/env python3
"""
Tests for MCP Server module
"""

import unittest
import os
import sys
import tempfile
from pathlib import Path
from unittest.mock import patch, MagicMock

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))


class TestMCPServer(unittest.TestCase):
    """Test cases for MCP Server"""
    
    def setUp(self):
        """Set up test fixtures"""
        # Set up environment
        self.original_env = os.environ.copy()
    
    def tearDown(self):
        """Clean up after tests"""
        os.environ.clear()
        os.environ.update(self.original_env)
    
    def test_get_bpm_guide_path_from_env(self):
        """Test getting guide path from environment variable"""
        from redflagbpm.mcp.mcp_server import get_bpm_guide_path
        
        # Create a temporary file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
            f.write("# Test Guide\n")
            temp_path = f.name
        
        try:
            os.environ['BPM_GUIDE_PATH'] = temp_path
            result = get_bpm_guide_path()
            self.assertEqual(str(result), temp_path)
        finally:
            if os.path.exists(temp_path):
                os.unlink(temp_path)
            if 'BPM_GUIDE_PATH' in os.environ:
                del os.environ['BPM_GUIDE_PATH']
    
    def test_get_bpm_guide_path_from_package(self):
        """Test getting guide path from package resources"""
        from redflagbpm.mcp.mcp_server import get_bpm_guide_path
        
        # Clear environment variable
        if 'BPM_GUIDE_PATH' in os.environ:
            del os.environ['BPM_GUIDE_PATH']
        
        # Try to get path from package
        result = get_bpm_guide_path()
        
        # Should return a Path object (temporary file) or None
        if result is not None:
            self.assertIsInstance(result, Path)
            # If it exists, it should be a markdown file
            if result.exists():
                self.assertTrue(result.suffix == '.md' or 'md' in str(result))
    
    @patch('redflagbpm.mcp.mcp_server.resources')
    def test_get_bpm_guide_path_package_fallback(self, mock_resources):
        """Test fallback when package resources are not available"""
        from redflagbpm.mcp.mcp_server import get_bpm_guide_path
        
        # Clear environment variable
        if 'BPM_GUIDE_PATH' in os.environ:
            del os.environ['BPM_GUIDE_PATH']
        
        # Mock resources to raise an error
        mock_resources.read_text.side_effect = FileNotFoundError("Resource not found")
        mock_resources.files.return_value.__truediv__.return_value.read_text.side_effect = FileNotFoundError()
        
        result = get_bpm_guide_path()
        # Should return None when resource is not found
        self.assertIsNone(result)
    
    def test_agent_id_from_env(self):
        """Test that agent ID can be set from environment"""
        from redflagbpm.mcp.mcp_server import AGENT_ID
        
        # Default value
        if 'BPM_AGENT_ID' in os.environ:
            del os.environ['BPM_AGENT_ID']
        
        # Need to reload module to test default
        import importlib
        import redflagbpm.mcp.mcp_server
        importlib.reload(redflagbpm.mcp.mcp_server)
        
        # Test with environment variable
        os.environ['BPM_AGENT_ID'] = 'TEST/AGENT'
        importlib.reload(redflagbpm.mcp.mcp_server)
        self.assertEqual(redflagbpm.mcp.mcp_server.AGENT_ID, 'TEST/AGENT')


class TestMCPServerIntegration(unittest.TestCase):
    """Integration tests for MCP Server (requires actual resources)"""
    
    def test_bpm_guide_resource_exists(self):
        """Test that BPM_Developer_Guide.md resource exists in package"""
        try:
            from importlib import resources
        except ImportError:
            try:
                import importlib_resources as resources
            except ImportError:
                self.skipTest("importlib.resources not available")
        
        try:
            # Try to access the resource
            if sys.version_info >= (3, 9):
                resource_path = resources.files("redflagbpm.resources")
                guide_file = resource_path / "BPM_Developer_Guide.md"
                # Check if it exists (may not work in all test environments)
                try:
                    content = guide_file.read_text(encoding='utf-8')
                    self.assertIsInstance(content, str)
                    self.assertGreater(len(content), 0)
                except (FileNotFoundError, AttributeError):
                    # Try alternative method
                    content = resources.read_text("redflagbpm.resources", "BPM_Developer_Guide.md", encoding='utf-8')
                    self.assertIsInstance(content, str)
                    self.assertGreater(len(content), 0)
            else:
                content = resources.read_text("redflagbpm.resources", "BPM_Developer_Guide.md", encoding='utf-8')
                self.assertIsInstance(content, str)
                self.assertGreater(len(content), 0)
        except (FileNotFoundError, ModuleNotFoundError, ImportError):
            # Resource might not be available in test environment
            # This is acceptable if package is not installed
            self.skipTest("BPM_Developer_Guide.md resource not available in test environment")


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

