#!/usr/bin/env python3
"""
Integration tests for MCP module
Tests the full workflow of processing and retrieving documentation
"""

import unittest
import sys
import tempfile
import os
from pathlib import Path

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

from redflagbpm.mcp.md_retriever import MDRetriever
from redflagbpm.mcp.mcp_server import get_bpm_guide_path, AGENT_ID, MD_RESOURCES


class TestMCPIntegration(unittest.TestCase):
    """Integration tests for MCP module"""
    
    def setUp(self):
        """Set up test fixtures"""
        self.temp_db = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
        self.temp_db.close()
        self.db_path = self.temp_db.name
    
    def tearDown(self):
        """Clean up after tests"""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
    
    def test_full_workflow(self):
        """Test the full workflow: process document, get index, get content"""
        # Create a test markdown document
        test_content = """# Getting Started [getting-started]
> Use this section when you need to understand the basics or start using the system.

This is the getting started section.

# Advanced Features [advanced]
> Use this section when you need to configure advanced settings or understand complex features.

Advanced features include:
- Feature 1
- Feature 2

# Troubleshooting [troubleshooting]
> Use this section when you encounter errors or need help resolving problems.

Common issues and solutions...
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
            f.write(test_content)
            temp_path = f.name
        
        try:
            retriever = MDRetriever(db_path=self.db_path)
            index = f"{AGENT_ID}/{MD_RESOURCES[0]}"
            
            # Process document
            retriever.process_document(index, temp_path)
            
            # Get index info
            index_info = retriever.get_index_info(AGENT_ID, MD_RESOURCES)
            
            # Verify index contains expected sections
            self.assertIn("getting-started", index_info)
            self.assertIn("advanced", index_info)
            self.assertIn("troubleshooting", index_info)
            self.assertIn("Getting Started", index_info)
            self.assertIn("Advanced Features", index_info)
            
            # Get content for a specific section
            doc = retriever.get_document_by_id(f"{index}#getting-started")
            self.assertIsNotNone(doc)
            self.assertEqual(doc['title'], "Getting Started")
            self.assertIn("basics", doc['keywords'].lower())
            self.assertIn("getting started section", doc['content'].lower())
            
            # Get content for another section
            doc = retriever.get_document_by_id(f"{index}#advanced")
            self.assertIsNotNone(doc)
            self.assertEqual(doc['title'], "Advanced Features")
            self.assertIn("Feature 1", doc['content'])
            
        finally:
            os.unlink(temp_path)
    
    def test_section_id_format(self):
        """Test that section IDs follow the expected format"""
        test_content = """# Test Section [test-id]

Content here.
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
            f.write(test_content)
            temp_path = f.name
        
        try:
            retriever = MDRetriever(db_path=self.db_path)
            index = f"{AGENT_ID}/{MD_RESOURCES[0]}"
            retriever.process_document(index, temp_path)
            
            # Document ID should follow format: index#section-id
            doc = retriever.get_document_by_id(f"{index}#test-id")
            self.assertIsNotNone(doc)
            self.assertEqual(doc['$id'], f"{index}#test-id")
            
        finally:
            os.unlink(temp_path)
    
    def test_multiple_sections_ordering(self):
        """Test that multiple sections maintain correct ordering"""
        test_content = """# First Section [first]

First content.

# Second Section [second]

Second content.

# Third Section [third]

Third content.
"""
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
            f.write(test_content)
            temp_path = f.name
        
        try:
            retriever = MDRetriever(db_path=self.db_path)
            index = f"{AGENT_ID}/{MD_RESOURCES[0]}"
            retriever.process_document(index, temp_path)
            
            # Get index info
            index_info = retriever.get_index_info(AGENT_ID, MD_RESOURCES)
            
            # Verify sections appear in order
            first_pos = index_info.find("first")
            second_pos = index_info.find("second")
            third_pos = index_info.find("third")
            
            self.assertLess(first_pos, second_pos)
            self.assertLess(second_pos, third_pos)
            
        finally:
            os.unlink(temp_path)


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

