#!/usr/bin/env python3
"""
Script simple para probar el servidor MCP localmente
Este script verifica que el servidor puede cargar y procesar la guía
"""

import sys
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


def test_server_setup():
    """Test that the server can be set up and load the guide"""
    print("Testing MCP Server Setup...")
    print("=" * 50)
    
    # Test 1: Check if guide path can be loaded
    print("\n1. Checking BPM Developer Guide path...")
    guide_path = get_bpm_guide_path()
    if guide_path and guide_path.exists():
        print(f"   ✓ Guide found at: {guide_path}")
        print(f"   ✓ File size: {guide_path.stat().st_size} bytes")
    else:
        print("   ✗ Guide not found!")
        return False
    
    # Test 2: Check if we can process the document
    print("\n2. Testing document processing...")
    try:
        import tempfile
        temp_db = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
        temp_db.close()
        retriever = MDRetriever(db_path=temp_db.name)
        index = f"{AGENT_ID}/{MD_RESOURCES[0]}"
        retriever.process_document(index, str(guide_path))
        print(f"   ✓ Document processed successfully")
        print(f"   ✓ Index: {index}")
        # Clean up
        os.unlink(temp_db.name)
    except Exception as e:
        print(f"   ✗ Error processing document: {e}")
        if 'temp_db' in locals():
            try:
                os.unlink(temp_db.name)
            except:
                pass
        return False
    
    # Test 3: Check if we can get index info
    print("\n3. Testing index retrieval...")
    sections = []
    try:
        # Recreate retriever with same DB
        retriever2 = MDRetriever(db_path=temp_db.name)
        retriever2.process_document(index, str(guide_path))
        index_info = retriever2.get_index_info(AGENT_ID, MD_RESOURCES)
        # Count sections
        import json
        # Extract JSON from the formatted string
        json_start = index_info.find('[')
        json_end = index_info.rfind(']') + 1
        if json_start >= 0 and json_end > json_start:
            sections = json.loads(index_info[json_start:json_end])
            print(f"   ✓ Index retrieved successfully")
            print(f"   ✓ Found {len(sections)} sections")
            if sections:
                print(f"   ✓ First section: {sections[0].get('title', 'N/A')}")
        else:
            print(f"   ✓ Index retrieved (format may vary)")
    except Exception as e:
        print(f"   ✗ Error retrieving index: {e}")
        if 'temp_db' in locals():
            try:
                os.unlink(temp_db.name)
            except:
                pass
        return False
    
    # Test 4: Check if we can get a specific section
    print("\n4. Testing section retrieval...")
    try:
        # Try to get the first section
        if sections:
            first_section_id = sections[0].get('id')
            if first_section_id:
                doc = retriever2.get_document_by_id(first_section_id)
                if doc:
                    print(f"   ✓ Section retrieved: {doc.get('title', 'N/A')}")
                    print(f"   ✓ Content length: {len(doc.get('content', ''))} characters")
                else:
                    print(f"   ✗ Section not found: {first_section_id}")
                    if 'temp_db' in locals():
                        try:
                            os.unlink(temp_db.name)
                        except:
                            pass
                    return False
        # Clean up
        if 'temp_db' in locals():
            os.unlink(temp_db.name)
    except Exception as e:
        print(f"   ✗ Error retrieving section: {e}")
        if 'temp_db' in locals():
            try:
                os.unlink(temp_db.name)
            except:
                pass
        return False
    
    print("\n" + "=" * 50)
    print("✓ All tests passed! Server is ready to use.")
    print("\nTo run the server:")
    print("  python3 -m redflagbpm.mcp")
    print("\nOr with venv:")
    print("  source venv/bin/activate")
    print("  python3 -m redflagbpm.mcp")
    return True


if __name__ == "__main__":
    success = test_server_setup()
    sys.exit(0 if success else 1)

