#!/usr/bin/env python3
"""
Test script for the Character Details MCP server.
Tests all available tools to verify functionality.
"""

import asyncio
import json
import sys

# MCP dependency with graceful fallback
try:
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    print("=" * 80)
    print("ERROR: MCP package is not installed.")
    print("Install it with: pip install mcp")
    print("=" * 80)
    sys.exit(1)


async def test_character_mcp():
    """Test the Character Details MCP server tools."""
    
    # Server parameters - using uv to run the character-details server
    server_params = StdioServerParameters(
        command="uv",
        args=[
            "run",
            "--directory",
            "tools/character-mcp",
            "character-details"
        ],
        env=None
    )
    
    print("=" * 80)
    print("Testing Character Details MCP Server")
    print("=" * 80)
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the session
            await session.initialize()
            
            # List available tools
            print("\n📋 Available Tools:")
            print("-" * 80)
            tools = await session.list_tools()
            for tool in tools.tools:
                print(f"  • {tool.name}: {tool.description}")
            
            # Test 1: Get character details for Aerith Gainsborough
            print("\n\n🔍 Test 1: Getting character details for Aerith Gainsborough")
            print("-" * 80)
            try:
                result = await session.call_tool(
                    "get_character",
                    arguments={
                        "name": "Aerith Gainsborough",
                        "franchise": "Final Fantasy VII"
                    }
                )
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        # Print first 500 chars to see structure
                        text = content.text
                        print(f"\nReceived {len(text)} characters of data")
                        print("\nFirst 500 characters:")
                        print(text[:500])
                        print("...")
            except Exception as e:
                print(f"❌ Error: {e}")
            
            # Test 2: List cached characters
            print("\n\n📚 Test 2: Listing cached characters")
            print("-" * 80)
            try:
                result = await session.call_tool("list_characters", arguments={})
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        print(content.text)
            except Exception as e:
                print(f"❌ Error: {e}")
            
            # Test 3: Generate image prompt
            print("\n\n🎨 Test 3: Generating image prompt for Aerith")
            print("-" * 80)
            try:
                result = await session.call_tool(
                    "generate_image_prompt",
                    arguments={
                        "name": "Aerith Gainsborough",
                        "franchise": "Final Fantasy VII",
                        "style": "anime",
                        "scene": "tending flowers in the church",
                        "extra_tags": "soft lighting, peaceful atmosphere"
                    }
                )
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        print("\nGenerated prompt:")
                        print(content.text)
            except Exception as e:
                print(f"❌ Error: {e}")
            
            # Test 4: Generate story context
            print("\n\n📖 Test 4: Generating story context for Aerith")
            print("-" * 80)
            try:
                result = await session.call_tool(
                    "generate_story_context",
                    arguments={
                        "name": "Aerith Gainsborough",
                        "franchise": "Final Fantasy VII",
                        "scenario": "Meeting Cloud for the first time in the Sector 5 church",
                        "include_abilities": True
                    }
                )
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        text = content.text
                        print(f"\nReceived {len(text)} characters of story context")
                        print("\nFirst 800 characters:")
                        print(text[:800])
                        print("...")
            except Exception as e:
                print(f"❌ Error: {e}")
            
            # Test 5: Try a different character - Princess Peach
            print("\n\n👑 Test 5: Getting character details for Princess Peach")
            print("-" * 80)
            try:
                result = await session.call_tool(
                    "get_character",
                    arguments={
                        "name": "Princess Peach",
                        "franchise": "Super Mario"
                    }
                )
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        text = content.text
                        print(f"\nReceived {len(text)} characters of data")
                        print("\nFirst 500 characters:")
                        print(text[:500])
                        print("...")
            except Exception as e:
                print(f"❌ Error: {e}")
            
            # Test 6: Generate image prompt for Princess Peach
            print("\n\n🎨 Test 6: Generating image prompt for Princess Peach")
            print("-" * 80)
            try:
                result = await session.call_tool(
                    "generate_image_prompt",
                    arguments={
                        "name": "Princess Peach",
                        "franchise": "Super Mario",
                        "style": "anime",
                        "scene": "in her castle throne room",
                        "extra_tags": "elegant, royal, pink dress"
                    }
                )
                print("✅ Success!")
                for content in result.content:
                    if hasattr(content, 'text'):
                        print("\nGenerated prompt:")
                        print(content.text)
            except Exception as e:
                print(f"❌ Error: {e}")
            
            print("\n" + "=" * 80)
            print("Testing Complete!")
            print("=" * 80)


if __name__ == "__main__":
    asyncio.run(test_character_mcp())
