#!/usr/bin/env python3
"""Test script to verify sinhala-mcp server works correctly."""

import asyncio
import os
import sys

# Fix Windows encoding
if sys.platform == "win32":
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# Add src to path
sys.path.insert(0, "src")

from mcp.client.session import ClientSession
from mcp.client.stdio import stdio_client, StdioServerParameters


async def test_server():
    """Test the MCP server."""
    print("🚀 Starting sinhala-mcp server test...")

    # Check if API key is set
    api_key = os.environ.get("GEMINI_API_KEY")
    if not api_key:
        print("⚠️  WARNING: GEMINI_API_KEY not set in environment")
        print("   Set it with: export GEMINI_API_KEY='your-key-here'")
        print("   Testing with mock response...\n")
    else:
        print(f"✅ GEMINI_API_KEY found (Masked: ************{api_key[-4:] if len(api_key) > 4 else '****'})\n")

    # Start the server
    server_params = StdioServerParameters(
        command=sys.executable,
        args=["-m", "sinhala_mcp.server"],
        env=os.environ.copy()
    )

    try:
        async with stdio_client(server_params) as (read, write):
            async with ClientSession(read, write) as session:
                # Initialize
                await session.initialize()

                # List available tools
                tools = await session.list_tools()
                print(f"📦 Available tools: {len(tools.tools)}")
                for tool in tools.tools:
                    print(f"   - {tool.name}: {tool.description}\n")

                # Test translate_sinhala_instruction
                if api_key:
                    print("🧪 Testing translate_sinhala_instruction...")
                    result = await session.call_tool(
                        "translate_sinhala_instruction",
                        arguments={"instruction": "mama simple login page ekk hadanna one"}
                    )

                    for content in result.content:
                        if hasattr(content, 'text'):
                            print(content.text)
                else:
                    print("⚠️  Skipping tool test (no API key)")

                print("\n✅ Server test completed successfully!")

    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()


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