"""
Test script for Chromium MCP Server
"""
import asyncio
import subprocess
import sys
import os
from mcp import ClientSession
from mcp.client.stdio import stdio_client
from mcp.types import CallToolResult

# Add parent directory to path to import source_fetch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

async def test_chromium_mcp():
    # Start the server as a subprocess
    server_process = subprocess.Popen([
        sys.executable, 
        "-c", 
        "from chromium_mcp_server import mcp; mcp.run(transport='stdio')"
    ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    
    try:
        # Wait a moment for the server to start
        await asyncio.sleep(1)
        
        # Create client session to test the server
        async with stdio_client(("python", ["-c", "from chromium_mcp_server import mcp; mcp.run(transport='stdio')"])) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                
                # Test the get_chromium_file tool
                result = await session.call_tool("get_chromium_file", {
                    "file_path": "chrome/app/chrome_main.cc",
                    "branch": "main"
                })
                
                print("Result from get_chromium_file:")
                print(result)
                
    except Exception as e:
        print(f"Error during test: {e}")
    finally:
        # Clean up server process
        server_process.terminate()
        server_process.wait()

def simple_test():
    """
    Simple function to test the core functionality without MCP framework
    """
    import base64
    import httpx
    
    # Test the core functions directly
    print("Testing core functions...")
    
    # Test URL extraction
    test_url = "https://source.chromium.org/chromium/chromium/src/+/main:chrome/app/chrome_main.cc"
    from chromium_mcp_server import extract_chromium_file_path
    extracted_path = extract_chromium_file_path(test_url)
    print(f"Extracted path from URL: {extracted_path}")
    
    # Test direct file fetching function
    print("\nTesting direct file fetching (this will make an HTTP request)...")
    try:
        import asyncio
        
        async def test_fetch():
            from chromium_mcp_server import fetch_chromium_source_file
            result = await fetch_chromium_source_file("chrome/app/chrome_main.cc", "main")
            print(f"Result length: {len(result) if isinstance(result, str) else 'non-string result'}")
            if isinstance(result, str) and len(result) > 100:
                print(f"First 200 chars: {result[:200]}...")
            else:
                print(f"Result: {result}")
        
        asyncio.run(test_fetch())
    except Exception as e:
        print(f"Error in fetching: {e}")

if __name__ == "__main__":
    print("Running simple test...")
    simple_test()